尝试比较两种实现有界阻塞队列的方法



有界阻塞队列当然是著名的。主要有两种方法来实现它。我试着了解哪种方法更好:方法1:使用计数信号量

void *producer(void *arg) {
int i;
for (i = 0; i < loops; i++) {
    sem_wait(&empty);           
    sem_wait(&mutex);           
    put(i);                     
    sem_post(&mutex);           
    sem_post(&full);            
}
}
void *consumer(void *arg) {
    int i;
    for (i = 0; i < loops; i++) {
        sem_wait(&full);            
        sem_wait(&mutex);           
        int tmp = get();            
        sem_post(&mutex);           
        sem_post(&empty);           
        printf("%dn", tmp);
    }
}

方法2:经典监控模式

class BoundedBuffer {
  private:
    int buffer[MAX];
    int fill, use;
    int fullEntries;
    pthread_mutex_t monitor; // monitor lock
    pthread_cond_t empty;
    pthread_cond_t full;
  public:
    BoundedBuffer() {
        use = fill = fullEntries = 0;
    }
    void produce(int element) {
        pthread_mutex_lock(&monitor);
        while (fullEntries == MAX) 
            pthread_cond_wait(&empty, &monitor); 
        //do something
        pthread_cond_signal(&full);             
        pthread_mutex_unlock(&monitor);
    }
    int consume() {
        pthread_mutex_lock(&monitor);
        while (fullEntries == 0)   
            pthread_cond_wait(&full, &monitor);           
        //do something
        pthread_cond_signal(&empty);            
        pthread_mutex_unlock(&monitor);
        return tmp;                
    }
}

我知道第二种方法可以解决很多其他问题。但是如何比较这两种方法呢?看来他们俩都能完成任务。是否有详细比较的链接?感谢你的帮助。谢谢

这两种方法之间的最大区别在于,第一种方法不使用pthread特定的函数(信号量不是pthread的一部分),因此不能保证在多线程环境中工作。

特别是,信号量不保护内存排序,所以在一个线程中编写的东西在另一个线程上可能不可读。互斥体适用于多线程消息队列。

最新更新