linux 条件变量

条件变量是线程可用的另一种同步机制。条件变量和互斥量一起使用时,允许线程以无竞争方式等待特定的条件发生。

条件本身是由互斥量保护的,线程在改变条件状态前必须先锁定互斥量。

 

注意:

条件变量Condition 主要描述的是 线程间的同步,即协作关系

Linux中条件变量通常涉及以下几个函数:

int pthread_cond_init(pthread_cond_t *cond, pthread_condattr_t *cond_attr);
int pthread_cond_wait(pthread_cond_t *cond, pthread_mutex_t *mutex);
int pthread_cond_timedwait(pthread_cond_t *cond, pthread_mutex_t *mutex);
int pthread_cond_signal(pthread_cond_t *cond);
int pthread_cond_broadcast(pthread_cond_t *cond);
int pthread_cond_destroy(pthread_cond_t *cond);

 

抄一个例子帮助理解:

 1 #include <pthread.h>
 2 
 3 struct msg
 4 {
 5     struct msg *next;
 6     /* */
 7 };
 8 
 9 struct msg *workq;
10 pthread_cond_t qready = PTHREAD_COND_INITIALIZER;
11 pthread_mutex_t qlock = PTHREAD_MUTEX_INITIALIZER;
12 
13 void process_msg(void)
14 {
15     struct msg *mp;
16     for (;;)
17     {
18         pthread_mutex_lock(&qlock);
19         while (workq == NULL)
20             pthread_cond_wait(&qready, &qlock);
21         mp = workq;
22         workq = mp->next;
23         pthread_mutex_unlock(&qlock);
24     }
25 }
26 
27 void enqueue_msg(struct msg *mp)
28 {
29     pthread_mutex_lock(&qlock);
30     mp->next = workq;
31     workq = mp;
32     pthread_mutex_unlock(&qlock);
33     pthread_cond_signal(&qready);
34 }
35 
36 
37   

 

posted @ 2019-08-06 17:33  hunterDing  阅读(65)  评论(0编辑  收藏