pthread_cond_wait()

pthread_cond_wai(条件等待) 
通常情况下,pthread_cond_wait() 和mutex一起配合使用。
用生产者与消费者的关系来看。
例如,有一个生产者,2个消费者。
 1 //定义全局的 互斥对象和条件等待对象
2
3 pthread_mutex_t mtx;
4
5 pthread_cond_t cond;
6
7 //消费者线程函数:
8
9 void threadproc(void * parm)
10
11 {
12
13 while(1)
14
15 {
16
17 pthread_mutex_lock(&mtx);//锁定mtx ,以防其他消费者线程 并发等待
18
19 pthread_cond_wait(&cond,&mtx);//首先解锁mtx,让其消费者线程或者生产者线程 获得机会去执行。然后休眠,不消耗任何CPU时间,等待被生产者唤醒
20
21 //...dosomthing
22
23 pthread_mutex_unlock(&mtx);//解锁
24
25 }
26
27 pthread_exit(0);
28
29 }
30
31 //生产者线程
32
33 void pdthreadproc(void * parm)
34
35 {
36
37 while(1)
38
39 {
40
41 pthread_mutex_lock(&mtx);//锁定mtx ,以防其他消费者线程 并发等待
42 //...dosomthing
43
44 pthread_cond_broadcastt(&cond,&mtx);//唤醒所有消费者线程,再次锁定mtx
45
46 pthread_mutex_unlock(&mtx);//解锁
47
48 }
49
50 pthread_exit(0);
51
52 }
pthread_cond_wait 为返回之前一直处于睡眠状态,那么当消费者线程被唤醒之后,它首先要去锁定mtx,获得独占权,其他线程干等!执行完毕之后再解锁,其他消费者线程 执行被唤醒之后的过程。
看了半天,终于弄懂了
posted @ 2012-01-13 13:08  rookie_zw  阅读(337)  评论(0)    收藏  举报