C++ 使用多线程间通信方式模拟消费者生产者模式demo

直接上代码

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

std::mutex mut;
std::queue<int> queData;
std::condition_variable cond;
#define MAX_NUM 20
int nCnt=0;
void Product()
{
    while (true) {
        std::unique_lock<std::mutex>lk(mut);
        cond.wait(lk,[]{
            if(queData.size() > MAX_NUM)
            {
                return false;
            }else
            {
                return true;
            }
        });

        queData.push(nCnt);
        std::cout << "this id " << std::this_thread::get_id()  <<", Insert a num,cur que size " << queData.size() << std::endl;
        nCnt++;
        cond.notify_one();
        lk.unlock();
        std::this_thread::sleep_for(std::chrono::seconds(1));
    }
}


void Customer()
{
    while (true) {
        std::cout << "wait " << std::endl;
        std::unique_lock<std::mutex>lk(mut);
        cond.wait(lk,[]{
           return queData.size() >0;
        });

        int cmd = queData.front();
        queData.pop();
         std::cout << "this id " << std::this_thread::get_id() <<", pop a num is " << cmd << ",cur que size is " << queData.size() << std::endl;
        cond.notify_one();
    }
}

int main()
{
    std::thread th = std::thread(Customer);
    std::thread th2 = std::thread(Product);

    th.join();
    th2.join();
    return 0;   //由于上面两个线程中存在while循环,没有退出条件,所以该行代码不会执行。可以按照实际条件(如回调函数)对上面两个线程中while条件修改。
}

Qt的.pro文件信息如下:

TEMPLATE = app
CONFIG += console c++11
CONFIG -= app_bundle
CONFIG -= qt

SOURCES += \
        main.cpp
LIBS += -lpthread

 直接结果如下:

关于线程中使用的互斥量和条件变量可参考链接:

C++多线程中共享变量同步问题_夜雨听萧瑟的博客-CSDN博客

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值