linux多线程实现生产者消费者

1. 初始化:

    条件变量采用的数据类型是pthread_cond_t, 在使用之前必须要进行初始化, 这包括两种方式:

  • 静态: 可以把常量PTHREAD_COND_INITIALIZER给静态分配的条件变量.
  • 动态: pthread_cond_init函数, 是释放动态条件变量的内存空间之前, 要用pthread_cond_destroy对其进行清理.

int pthread_cond_init(pthread_cond_t *restrict cond, pthread_condattr_t *restrict attr);
int pthread_cond_destroy(pthread_cond_t *cond);

 #include <stdio.h>
 #include <pthread.h>
 #include <unistd.h>
 //条件变量生产者和消费者
 pthread_cond_t condc,condp;
 pthread_mutex_t the_mutex;
 
 unsigned int buffer = 0;//全局共享资源
 const int MAX = 100;
 void *producer(void *ptr){
     for(int i = 1; i < MAX; i++){
         pthread_mutex_lock(&the_mutex);
         //producer在当buffer内容生产中便进入等待
         while(buffer != 0) pthread_cond_wait(&condp, &the_mutex);
         sleep(1);
         buffer = i;
        printf("producer pthread produce one production %d.\n", i);
       //生产者线程生产完成
        pthread_cond_broadcast(&condc);//唤醒两个消费者线程
        pthread_mutex_unlock(&the_mutex);
     }
     pthread_exit(0);
 }

 void *consumer1(void *ptr){
     for(int i = 1; i < MAX; i++){
         pthread_mutex_lock(&the_mutex);
        while(buffer == 0)//生产者生产的产品消费完,消费者线程阻塞
           pthread_cond_wait(&condc, &the_mutex);    
         printf("consumer1 pthread consume one production %d.\n", buffer);
         buffer = 0;
        pthread_cond_signal(&condp);//并且发送信号给生产者线程
         pthread_mutex_unlock(&the_mutex);
    }
     pthread_exit(0);
 }
 void *consumer2(void *ptr){
     for(int i = 1; i < MAX; i++){
        pthread_mutex_lock(&the_mutex);
        while(buffer == 0) pthread_cond_wait(&condc, &the_mutex);    
         printf("consumer2 pthread consume one production %d.\n", buffer);
        buffer = 0;
         pthread_cond_signal(&condp);
        pthread_mutex_unlock(&the_mutex);
    }
    pthread_exit(0);
 }
 
 int main(void){
     pthread_t pro, con1, con2;
    pthread_mutex_init(&the_mutex,0);
    pthread_cond_init(&condc,0);//动态初始化条件变量
     pthread_cond_init(&condp,0);
     pthread_create(&con1, 0, consumer1, 0);
     pthread_create(&pro, 0, producer, 0);
    pthread_create(&con2, 0, consumer2, 0);
     pthread_join(pro, 0);
    pthread_join(con1, 0);
    pthread_join(con2, 0);
     pthread_cond_destroy(&condc);
    pthread_cond_destroy(&condp);
     pthread_mutex_destroy(&the_mutex);
     return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陌上花开缓缓归以

你的鼓励将是我创作的最大动力,

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值