linux ptheard 生产者消费者

 1 #include <stdio.h>
 2 #include <stdlib.h>
 3 #include <pthread.h>
 4 
 5 pthread_mutex_t mutex;
 6 pthread_cond_t cond_full;
 7 pthread_cond_t cond_empty;
 8 
 9 int g_iBufSize = 0;
10 
11 void *thread_producer(void* arg)
12 {
13     while(true)
14     {
15         printf("thread_producer:pthread_mutex_lock ");
16         pthread_mutex_lock(&mutex);
17         // 拿到lock就可以访问,不会冲突,但是不一定满足条件,cond是为了在满足条件的时候通知另一个进程
18         if(0 != g_iBufSize) //如果条件不满足就调用wait函数等待条件满足
19         {
20             printf("thread_producer:pthread_cond_wait cond_empty  ");
21             pthread_cond_wait(&cond_empty, &mutex); // 这句话的前提是先有锁,这时候会自动先解锁,等到时机来临在加锁
22         }
23         
24         //前面的wait操作已经包含了枷锁,这里直接访问
25         printf("thread_producer>>>>> ");
26         g_iBufSize = 1;
27         
28         printf("thread_producer: pthread_cond_signal ");
29         pthread_cond_signal(&cond_full);
30    
31         pthread_mutex_unlock(&mutex);
32     }
33     return NULL;
34 }
35 
36 void *thread_consumer(void* arg)
37 {
38     while(true)
39     {
40         printf("thread_consumer:pthread_mutex_lock ");
41         pthread_mutex_lock(&mutex);
42         if(0 == g_iBufSize)
43         {
44             printf("thread_consumer: pthread_cond_wait ");
45             pthread_cond_wait(&cond_full, &mutex);
46         }
47         
48         printf("thread_consumer>>> ");
49         g_iBufSize = 0;
50         
51         printf("thread_consumer: pthread_cond_signal ");
52         pthread_cond_signal(&cond_empty);
53         
54         pthread_mutex_unlock(&mutex);
55 
56     }
57     return NULL;
58 }
59 
60 //g++ -o bin1 -lpthread mutithread.cpp
61 
62 int main()
63 {
64     void *retval1, *retval2;
65     pthread_t thread_id_1, thread_id_2;
66     
67     pthread_mutex_init(&mutex, NULL);
68     pthread_cond_init(&cond_full, NULL);
69     pthread_cond_init(&cond_empty, NULL);
70     
71     pthread_cond_signal(&cond_empty);
72     pthread_create(&thread_id_1, NULL, thread_producer, NULL);//int pthread_create(pthread_t *tidp, const pthread_attr_t *attr, (void*)(*start_rtn)(void*),void *arg);
73     pthread_create(&thread_id_2, NULL, thread_consumer, NULL);
74      
75     pthread_join(thread_id_1, &retval1); // 阻塞等线程执行完
76     pthread_join(thread_id_2, &retval2);
77     
78     pthread_cond_destroy(&cond_full);
79     pthread_cond_destroy(&cond_empty);
80     pthread_mutex_destroy(&mutex);
81     
82     return 0;
83 }
原文地址:https://www.cnblogs.com/GhostZCH/p/4421062.html