代码示例:

#include <iostream>             
#include <thread>         
#include <chrono>      
#include <mutex>
#include <deque>
#include <condition_variable>

std::deque<int> global_deque;
std::mutex global_mutex;
std::condition_variable global_ConditionVar;

// 生产者线程
void Producer()
{
    while (true)
    {
        // 休眠5毫秒
        std::this_thread::sleep_for(std::chrono::milliseconds(5));

        std::unique_lock<std::mutex> lock(global_mutex);
        global_deque.push_front(1);
        std::cout << "生产者生产了数据" << std::endl;
        global_ConditionVar.notify_all();
    }
}

// 消费者线程
void Consumer()
{
    while (true)
    {
        std::unique_lock<std::mutex> lock(global_mutex);

        // 当队列为空时返回false,则一直阻塞在这一行
        global_ConditionVar.wait(lock, [] {return !global_deque.empty(); });
        global_deque.pop_back();

        std::cout << "消费者消费了数据" << std::endl;
        global_ConditionVar.notify_all();
    }
}

int main()
{

    std::thread consumer_Thread(Consumer);
    //std::thread consumer_Thread1(Consumer);

    std::thread producer_Thread(Producer);

    consumer_Thread.join();
    //consumer_Thread1.join();
    producer_Thread.join();


    getchar();
    return 0;
}

如果您觉得对您有帮助,可以请站长喝一杯咖啡哦!

记得在赞赏备注里写上您的昵称

您可在本站资助名单中查看你的打赏记录哦!

支付宝扫一扫

微信扫一扫

金额随意,礼清义重

当前分类随机文章推荐

全站随机文章推荐

关于本站站长 StubbornHuang
C++11/std::condition_variable – 生产者消费者模型-StubbornHuang Blog纵使晴明无雨色,入云深处亦沾衣。