C++11并发学习之五:生产者与消费者

C++11并发学习之四:线程同步(续)中实际上用条件变量实现了一个简单的单生产者-单消费者模型,也就是一个生产者和一个消费者。

本文将实现单生产者-多消费者模型、多生产者-单消费者模型和多生产者-多消费者模型。前两种实际上是简化版的多生产者-多消费者,因此只需要实现第三种。

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

int counter=0;
int maxSize = 30;
std::mutex mtx;
std::queue<int> dataQuene; // 被生产者和消费者共享

std::condition_variable producer, consumer;  // 条件变量是一种同步机制,要和mutex以及lock一起使用

void func_consumer()
{
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(1000));// 消费者比生产者慢

        std::unique_lock<std::mutex> lck(mtx);
        consumer.wait(lck, [] {return dataQuene.size() != 0; });     // 消费者阻塞等待, 直到队列中元素个数大于0
        int num=dataQuene.front();
        dataQuene.pop();
        std::cout << "consumer " << std::this_thread::get_id() << ": "<< num <<std::endl;

        producer.notify_all();                                       // 通知生产者当队列中元素个数小于maxSize
    }
}

void func_producer()
{
    while (true)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(900));  // 生产者稍微比消费者快
        std::unique_lock<std::mutex> lck(mtx);
        producer.wait(lck, [] {return dataQuene.size() != maxSize; });// 生产者阻塞等待, 直到队列中元素个数小于maxSize

        ++counter;
        dataQuene.push(counter);
        std::cout << "producer " << std::this_thread::get_id() << ": "<< counter <<std::endl;

        consumer.notify_all();                                        //通知消费者当队列中的元素个数大于0
    }
}

int main()
{
    std::thread consumers[2], producers[2];

    // 两个生产者和消费者
    for (int i = 0; i < 2; ++i)
    {
        consumers[i] = std::thread(func_consumer);
        producers[i] = std::thread(func_producer);
    }

    for (int i = 0; i < 2; ++i)
    {
        producers[i].join();
        consumers[i].join();
    }

    system("pause");
    return 0;
}

运行结果

参考链接:生产者-消费者,使用C++11的版本_sicolex的博客-CSDN博客_c++11 生产者消费者

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

草上爬

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值