生产者消费者的例子-使用条件变量

 1 #include <stdio.h> 
 2 #include <stdlib.h> 
 3 #include <time.h> 
 4 #include <pthread.h>
 5 
 6 pthread_mutex_t x;
 7 pthread_cond_t cv;
 8 static int s=0;
 9 
10 int rand_num[100]={0};
11 int  rd=0,wt=0;
12 
13 void* threadConsumer(void* param)
14 {
15    int r;
16    int tid=*(int*)param;
17    while(1)
18    { 
19         pthread_mutex_lock(&x);
20         while(s<=0)
21         { 
22             printf("%u waiiting...
",tid);
23             pthread_cond_wait(&cv,&x);
24         }
25         r = rd;
26         printf("%u get number %d %d
",tid,r,rand_num[r]);
27         rand_num[r]=0;
28         rd=++rd%100;
29         
30         s--;
31             
32         pthread_mutex_unlock(&x);
33         usleep(0);
34     }
35 
36 }
37 
38 void* threadProduct(void* param)
39 {
40     int i=0;
41     rd=wt=0;
42     
43     while(1)
44     {
45         unsigned int seed = time(NULL);
46         int left=0,left2;
47         pthread_mutex_lock(&x);
48 
49         left=(wt>=rd)?(100-wt+rd):(rd-wt);
50         if(left==0||s==100)
51         {
52           pthread_mutex_unlock(&x);
53           usleep(0);
54           continue;
55         }
56 
57         left2=left;
58         
59         while(left>0)
60         { 
61             rand_num[wt]=rand_r(&seed);
62             wt=++wt%100;
63             s++;
64             left--;
65         }
66         pthread_mutex_unlock(&x);
67         
68         pthread_cond_broadcast(&cv);
69                 printf("new add %d
",left2);
70                 usleep(0);
71     }
72 }
73 
74 int main(int arc ,char** argv)
75 {
76     int i=0;
77     pthread_t tids[101]={0};
78     pthread_attr_t attr;
79 
80     pthread_attr_init(&attr);
81     
82     for(i=0;i<50;i++)
83     {
84         pthread_create(&tids[i],&attr,threadConsumer,(void*)(tids+i));
85     }
86 
87     pthread_create(&tids[i],&attr,threadProduct,(void*)(tids+100));
88     
89     pthread_join(tids[i],NULL);
90     
91     return 0;
92     
93 }
原文地址:https://www.cnblogs.com/wangshenyang/p/5781079.html