首页 > 其他 > 详细

生产者消费者模型 producer consumer 设计模式 异步 解耦

时间:2020-07-18 09:41:37      阅读:66      评论:0      收藏:0      [点我收藏+]
#include <iostream>
#include <thread>
#include <chrono>
#include <mutex>
#include <deque>
#include <condition_variable>
using namespace std;
//template<typename T>
class pc {
public:
    pc() {};
    pc(int size):_size(size) {
    };
    pc(const pc &) = delete;
    pc & operator= (const pc &) = delete;
    void p(int t) { 
        std::unique_lock<std::mutex> _lock(_mtx);
        _cvp.wait(_lock, [&] {return _q.size() <_size; });
        _q.emplace_back(t); 
        std::cout << std::this_thread::get_id() << ":[p]" << t <<"[size]:"<< _q.size() << std::endl;
        _cvc.notify_all();
    };
    int c() {
        std::unique_lock<std::mutex> _lock(_mtx);
        _cvc.wait(_lock, [&] {return _q.size() >0; });
        int r = _q.front();
        std::cout << std::this_thread::get_id() << ":[c]" << r << "[size]:" << _q.size() << std::endl;
        _q.pop_front();
        _cvp.notify_all();
        return r;
    };
private:
    int _size;
    std::deque<int> _q;
    std::mutex _mtx;
    std::condition_variable _cvp;
    std::condition_variable _cvc;

};

int main() {
    pc mydeque(10);
    std::thread(
        [&] {
        int i = 10;
        while (true)
        {
            mydeque.p(i++);
            this_thread::sleep_for(chrono::milliseconds(300));
        }
    }
    ).detach();
    std::thread(
        [&] {
        while (true)
        {
            int r= mydeque.c();
            this_thread::sleep_for(chrono::milliseconds(1600));
            
        }
        
    }
    ).detach();
    while (true)
    {
    }
}

 

生产者消费者模型 producer consumer 设计模式 异步 解耦

原文:https://www.cnblogs.com/liuguoyao514257665/p/13334270.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!