#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