32 #include<stdio.h>
33 #include<pthread.h>
34 #include<unistd.h>
35 #include<stdlib.h>
36 #include<string.h>
37 pthread_mutex_t mutex;
38 pthread_cond_t condt;
39 pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
40 pthread_cond_t condt=PTHREAD_COND_INITIALIZER;
41 typedef struct food1 {
42 struct food1 *next;
43 int food_num;
44 }food;
45 food *head=NULL;
46 food *hanburge=NULL;
47 int num=500;
48 void *product(void *arg)
49 {
50 while(1){
51 pthread_mutex_lock(&mutex);
52 hanburge=malloc(sizeof(food));
53 hanburge->next=head;
54 hanburge->food_num=num++;
55 printf("have product:%d\n",hanburge->food_num);
56 head=hanburge;
57 pthread_mutex_unlock(&mutex);
58 pthread_cond_signal(&condt);//发送条件变量给等待的线程
59 sleep(rand()%3);
60 }
61 }
62
63 void *commuse(void *arg)
64 {
65 while(1){
66 pthread_mutex_lock(&mutex);
67 while(head==NULL){
68 pthread_cond_wait(&condt,&mutex);//解开互斥锁,等待条件变量到来
69 }
70 printf("commuse get foodnum:%d\n",head->food_num);
71 hanburge=head;
72 head=head->next;
73 free(hanburge);
74 pthread_mutex_unlock(&mutex);
75 sleep(rand()%3);
76 }
77 }
78
79 void main(void)
80 {
81 pthread_t pthpid,compid1;
82 pthread_create(&pthpid,NULL,product,NULL);
83
84 pthread_create(&compid1,NULL,commuse,NULL);
85
86 while(1);
87
88 }
条件变量的优点:相较于单独使用互斥锁,条件变量可以减少竞争,限制某一方对全局变量的使用。而另一方可以随行所欲的对全局变量进行操作。