C++实现生产者和消费者模型

头文件 和 全局变量在这里插入图片描述

消费者

在这里插入图片描述

生产者

在这里插入图片描述

main函数

在这里插入图片描述

代码

#include <iostream>
#include<thread>
#include<mutex>
#include<condition_variable>
#include<queue>

using namespace std;

//任务队列
queue<int>products ;
mutex m ;
condition_variable cond ;
bool notify = false ;//通知
bool done = false ;

void consumer(){
    
    while(!done){
        
        //上锁保护共享资源,unique_lock一次实现上锁和解锁
        unique_lock<mutex>lk(m);
        //等待生产者者通知有资源
        while(!notify){
            
            cond.wait(lk);
        }

        //要是队列不为空的话
        while(!products.empty()){

            cout<<"consumer:"<<products.front()<<endl;
            products.pop();
            //通知生产者仓库容量不足,生产产品
            notify = false ;
            cond.notify_one();
        }
    }
}

void producer(){
    
    int i ;
    for(i=0;i<10;i++){
		//主动让出cpu,不参与cpu 的本次调度,让其他线程使用,
		//等一秒后再参与调度
		//this_thread::sleep_for(chrono::seconds(1));
        unique_lock<mutex>lk(m);
        cout<<"producer..."<<i<<endl;
        //如果仓库中有产品,就等待消费者消费完后在生产
        while(notify||!products.empty()){
            cond.wait(lk);
        }
        //当前仓库里面没有东西了,就将产品装入仓库
        products.push(i);
        //设置有产品的通知
        notify = true ;
        //通知消费者可以取产品了
        cond.notify_one();
        
    }   
    

    //通知消费者端不生产了
    done = true ;
    cond.notify_one();
}   

int main()
{

    thread t1(producer);
    thread t2(consumer);
    t1.join();
    t2.join();
    return 0;
}


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值