代码实现:
int num = 0;
pthread_mutex_t mutex ;
pthread_cond_t condition;
void *producer(void *arg)
{
pthread_mutex_lock(&mutex);
num ++ ;
if(num == 1)
pthread_cond_signal(&condition);
pthread_mutex_unlock(&mutex);
}
void *cusumer(void* arg)
{
phtread_mutex_lock(&mutex);
while(num == 0)
{
pthread_cond_wait(&cond,&mutex);
}
num--;
pthread_mutex_unlock(&mutex);
}
首先,条件变量一定要和互斥锁一起使用,因为防止多个线程同时请求pthread_cond_wait()
pthread_cond_wait()
做了3个操作{
1.释放已经获得的锁.
2.进入休眠.(挂起)
3.等待某个条件成立,苏醒过来
}
linux内核将其做成了一个原子性的操作;
pthread_cond_signal();
当条件成立的时候,唤醒等待的线程;