下面这份代码是我的书写方式:
static bool alive = true;
static int count = 0;
pthread_mutex_t mutex;
pthread_cond_t cond;
void producer()
{
pthread_mutex_lock(&mutex); //加互斥锁
//...do something here, queue.insert() ...or create something...
count++;
//如果像下面这样写,则consumer阻塞到pthread_mutex_lock(&mutex)
//比pthread_cond_wait(&cond, &mutex)先得到互斥锁控制权。
pthread_mutex_unlock(&mutex); //解互斥锁
pthread_cond_signal(&cond); //唤醒wait(),如果没有wait则什么都不做
//如果像下面这样写,则consumer阻塞到pthread_mutex_lock(&mutex)
//比pthread_cond_wait(&cond, &mutex)可能后得到互斥锁控制权。
pthread_cond_signal(&cond); //唤醒wait(),如果没有wait则什么都不做
pthread_mutex_unlock(&mutex); //解互斥锁
}
void consumer()
{
pthread_mutex_lock(&mutex);//加互斥锁
while(alive && 0 == count) { //仅在count == 0 时才wait,而且是while()不是if(),经过测试必须得是while,why?
//因为pthread_cond_wait(&cond, &mutex)分为unlock-》wait-》lock,当像producer像第一种书写顺序,则即使得到signal,
//那么无法获得互斥锁控制权,那么将阻塞在lock上,相当于回退2行到 pthread_mutex_lock(&mutex);
pthread_cond_wait(&cond, &mutex); //内部先解互斥锁才睡眠,等唤醒后自动加回互斥锁。
}
//... do something here, queue.get() ... or use & delete something
count --;
pthread_mutex_lock(&mutex);//解互斥锁
}转载请注明出处,谢谢: http://blog.youkuaiyun.com/sprintfwater/article/details/21190859
本文详细解析了生产者-消费者模式中的线程同步问题,包括如何使用互斥锁和条件变量来协调生产者与消费者的运行,确保数据的一致性和同步。通过具体的代码示例展示了两种不同的信号发送时机对消费线程的影响。
2万+

被折叠的 条评论
为什么被折叠?



