条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起;另一个线程使"条件成立"(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。

一 pthread_cond_wait定义:

函数原型:int   pthread_cond_wait(pthread_cond_t   *cond,   pthread_mutex_t   *mutex)  

参数: cond 条件变量  mutex 互斥锁
第一个参数*cond是指向一个条件变量的指针。第二个参数*mutex则是对相关的互斥锁的指针。

二 pthread_cond_wait示例理解

pthread_cond_wait的机制比较难里理解,是条件变量中重要的成分。条件变量用于线程间同步,那么pthread_cond_wait必须和互斥锁同时作用在一个线程里,它同时起到对资源的加锁和解锁,看下面的示例:


程序创建了2个新线程使他们同步运行,实现进程t_b打印9以内3的倍数,t_a打印其他的数,程序开始线程t_b不满足条件等待,线程t_a运行使a循环加1并打印。直到i为3的倍数时,线程t_a发送信号通知进程t_b,这时t_b满足条件,打印i值。

 1 #include<pthread.h>
 2 #include<unistd.h>
 3 #include<stdio.h>
 4 #include<stdlib.h>
 5 
 6 pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;/*初始化互斥锁*/
 7 pthread_cond_t  cond = PTHREAD_COND_INITIALIZER;//init cond
 8 
 9 void *thread1(void*);
10 void *thread2(void*);
11 
12 int i = 1; //global
13 
14 int main(void){
15     pthread_t t_a;
16     pthread_t t_b;//two thread
17 
18     pthread_create(&t_a,NULL,thread2,(void*)NULL);
19     pthread_create(&t_b,NULL,thread1,(void*)NULL);//Create thread
20 
21     pthread_join(t_b,NULL);//wait a_b thread end
22     pthread_mutex_destroy(&mutex);
23     pthread_cond_destroy(&cond);
24    exit(0);
25 }
26 
27 void *thread1(void *junk){
28     for(i = 1;i<= 9; i++){
29         pthread_mutex_lock(&mutex); //互斥锁
30         printf("call thread1 \n");
31         if(i%3 == 0)
32             pthread_cond_signal(&cond); //send sianal to t_b
33         else
34             printf("thread1: %d\n",i);
35         pthread_mutex_unlock(&mutex);
36         sleep(1);
37     }
38 }
39 
40 void *thread2(void*junk){
41     while(i < 9)
42     {
43         pthread_mutex_lock(&mutex);
44         printf("call thread2 \n");
45         if(i%3 != 0)
46             pthread_cond_wait(&cond,&mutex); //wait
47          printf("thread2: %d\n",i);
48         pthread_mutex_unlock(&mutex);
49         sleep(1);
50     }
51 }                                    
View Code

相关文章: