C语言:生产者消费者(线程-互斥量与条件变量)

 

#iinclude <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
    
struct Msg                //共享数据
{
        int num;
        struct Msg *next;
};

struct Msg *head;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;    //定义并初始化一个互斥量
pthread_cond_t has_data = PTHREAD_COND_INITIALIZER;    //定义并初始化一个条件变量

void err_thread(int ret,char *str)  //如果线程创建失败,则返回失败的原因,并退出线程....
{
        if(ret != 0){
                fprintf(stderr,"%s:%s\n",str,strerror(ret));
                pthread_exit(NULL);
        }
}

void *produser(void *arg)    //生产者
{
        while(1){
                struct Msg *food = (struct Msg *)malloc(sizeof(struct Msg));    //生产一个食物
                food->num = rand() % 1000 + 1;        //初始化食物,模拟生产了一个数据
                printf("--produser %d\n",food->num);

                pthread_mutex_lock(&mutex);          //加锁
                food->next = head;                  //写公共区域      
                head = food;
                pthread_mutex_unlock(&mutex);       //解锁

                pthread_cond_signal(&has_data);    //唤醒阻塞在条件变量 has_data上的线程

                sleep(rand() % 3);
        }
}

void *consumer(void *arg)    //消费者
{
        struct Msg *food;

        while(1){
                pthread_mutex_lock(&mutex);                    //加锁 互斥量
                if(head == NULL){    
                        pthread_cond_wait(&has_data,&mutex);    //阻塞等待条件变量,解锁
                }                                               //pthread_cond_wait 返回时,重新加锁                         

                food = head;
                head = food->next;

                pthread_mutex_unlock(&mutex);                   //解锁
                printf("-------------------consumer:%d\n",food->num);

                free(food);
                sleep(rand() % 3);
        }
}

int main()
{
        int ret;
        pthread_t pid,cid;

        srand(time(NULL));

        ret = pthread_create(&pid,NULL,produser,NULL);    //生产者线程
        if(ret != 0){
                err_thread(ret,"pthread_creat error");
        }

        ret = pthread_create(&cid,NULL,consumer,NULL);    //消费者线程
        if(ret != 0){
                err_thread(ret,"pthread_creat error");
        }

        pthread_join(pid,NULL);
        pthread_join(cid,NULL);

        return 0;
}

 

  • 0
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 3
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

枕上

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

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

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

打赏作者

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

抵扣说明:

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

余额充值