互斥锁与条件变量实现生产者消费模式

#include<stdio.h>
#include<pthread.h>
#include<stdlib.h>
#include<string.h>
#include<unistd.h>
//互斥量
pthread_mutex_t mutex;
//条件变量
pthread_cond_t cond;
//定义结构体
typedef struct Node
{
        int data;
        struct Node *next;
}NODE;
//头插法
NODE *head = NULL;
//生产者处理函数
void *producer(void *arg)
{
        //定义一个节点
        NODE *pNode = NULL;
        while(1)
        {
                //开辟堆内存
                pNode = (NODE *)malloc(sizeof(NODE));
                if(pNode==NULL)
                {
                        printf("malloc error\n");
                        exit(-1);
                }
                //随机数赋值
                pNode->data = rand()%1000;
                printf("P:[%d]\n", pNode->data);
                //加锁
                pthread_mutex_lock(&mutex);
                pNode->next = head;

                head = pNode;
                pthread_mutex_unlock(&mutex);
                //通知消费者线程解除阻塞
                pthread_cond_signal(&cond);
                sleep(rand()%3);
        }
}

//消费者线程
void *consumer(void *arg)
{
        NODE *cNode = NULL;
        while(1)
        {
                pthread_mutex_lock(&mutex);
                //head为空阻塞
                if(head==NULL)
                {
                        pthread_cond_wait(&cond, &mutex);
                }

                printf("C:[%d]\n", head->data);
                cNode = head;
                head = head->next;
                //解锁
                pthread_mutex_unlock(&mutex);
                //删除头节点
                free(cNode);
                cNode = NULL;
                sleep(rand()%3);

        }
}

int main()
{
        int ret;
        pthread_t ptid, ctid;
        //初始化互斥量
        pthread_mutex_init(&mutex, NULL);
        //初始化条件变量
        pthread_cond_init(&cond, NULL);
        //创建生产者
        ret = pthread_create(&ptid, NULL, producer, NULL);
        if(ret!=0)
        {
                printf("pthread_create error, [%s]\n", strerror(ret));
                return -1;
        }
        //创建消费者
        ret = pthread_create(&ctid, NULL, consumer, NULL);
        if(ret!=0)
        {
                printf("pthraed_create error, [%s]\n", strerror(ret));
                return -1;
        }
        //阻塞线程结束
        pthread_join(ptid, NULL);
        pthread_join(ctid, NULL);
        //释放互斥锁
        pthread_mutex_destroy(&mutex);
        //释放条件变量
        pthread_cond_destroy(&cond);
        return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值