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\n ");
16         pthread_mutex_lock(&mutex);
17          //  拿到lock就可以访问,不会冲突,但是不一定满足条件,cond是为了在满足条件的时候通知另一个进程
18           if( 0 != g_iBufSize)  // 如果条件不满足就调用wait函数等待条件满足
19          {
20             printf( " thread_producer:pthread_cond_wait cond_empty \n ");
21             pthread_cond_wait(&cond_empty, &mutex);  //  这句话的前提是先有锁,这时候会自动先解锁,等到时机来临在加锁
22          }
23         
24          // 前面的wait操作已经包含了枷锁,这里直接访问
25          printf( " thread_producer>>>>>\n ");
26         g_iBufSize =  1;
27         
28         printf( " thread_producer: pthread_cond_signal\n ");
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\n ");
41         pthread_mutex_lock(&mutex);
42          if( 0 == g_iBufSize)
43         {
44             printf( " thread_consumer: pthread_cond_wait\n ");
45             pthread_cond_wait(&cond_full, &mutex);
46         }
47         
48         printf( " thread_consumer>>>\n ");
49         g_iBufSize =  0;
50         
51         printf( " thread_consumer: pthread_cond_signal\n ");
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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值