先说点其他的,pthread_cond_wait(cond, lock)在语义上等于pthread_mutex_unlock(lock), pthread_cond_wait(cond), pthread_mutex_lock(lock),但却不能拆开运行,在第一句和第二句之间有可能会错失信号。
下面是一个真实的模型,这个模型中有一个producer和多个consumer,producer有生产限制和结束标志,为简化过程,producer和consumer等待在一个条件变量上。
void producer()
{
pthread_mutex_lock(&res_lock);
while (RES.count == RES.MAX) {
pthread_cond_wait(&res_cond, &res_lock);
}
Produce(&RES);
if (RES.count == 1) {
pthread_cond_broadcast(&res_cond);
}
pthread_cond_unlock();
}
void consumer()
{
pthread_mutex_lock(&res_lock);
while (!RES.nomore && RES.count == 0) {
pthread_cond_wait(&res_cond, &res_lock);
}
pthread_cond_broadcast(&res_cond);
if (RES.nomore && RES.count == 0) {
pthread_mutex_unlock(&res_lock);
return;
}
Consume(&RES);
pthread_mutex_unlock(&res_lock);
}
当producer的产量达到RES.MAX最大限制时,便等待在res_cond上。当producer生产完全结束时,将RES.nomore置为true。如果producer生产完全结束,consumer会结束条件测试并退出。