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博客

猜你喜欢

转载自blog.csdn.net/hanxiaoyong_/article/details/130846098