#include <iostream> #include <thread> #include <chrono> #include <mutex> #include <deque> #include <condition_variable> template<typename T> class pc { public: pc() {}; pc(int size) :_size(size) { }; pc(const pc &) = delete; pc & operator= (const pc &) = delete; void pc<T>::p(T t) { std::unique_lock<std::mutex> _lock(_mtx); _cvp.wait(_lock, [&] {return true == run ? (_q.size() < _size) : true; }); if (false == run) return; _q.emplace_back(t); std::cout << std::this_thread::get_id() << ":[p]" << t << "[size]:" << _q.size() << std::endl; _cvc.notify_all(); }; T pc<T>::c() { std::unique_lock<std::mutex> _lock(_mtx); _cvc.wait(_lock, [&] {return true == run ? (_q.size() > 0) : true; }); if (false == run) return -1; T 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; }; int size() { return _q.size(); }; void stop() { run = false; _cvp.notify_all(); _cvc.notify_all(); } void start() { run = true; } private: bool run = true; int _size; std::deque<T> _q; std::mutex _mtx; std::condition_variable _cvp; std::condition_variable _cvc; }; int main(int argc, char* argv[]) { bool run = true; pc<double> dqRead(9); pc<double> dqWrite(9); //监控deque使用情况 std::thread([&] { while (run) { std::this_thread::sleep_for(std::chrono::seconds(1)); std::cout << "ReadDequeSize:" << dqRead.size() << " WriteDequeSize:" << dqWrite.size() << std::endl; } std::cout << "监控deque使用情况 exit" << std::endl; }).detach(); //数据处理线程 std::thread([&] { while (run) { auto r = dqRead.c(); dqWrite.p(r); std::this_thread::sleep_for(std::chrono::seconds(1)); } std::cout << "数据处理线程 exit" << std::endl; }).detach(); //写入hdb数据线程 std::thread([&] { while (run) { auto r = dqWrite.c(); std::this_thread::sleep_for(std::chrono::seconds(1)); } std::cout << "写入hdb数据线程 exit" << std::endl; }).detach(); //主线程读取market数据 int i = 7; while (true) { if (0 == i--) break; dqRead.p(i*1.11); std::this_thread::sleep_for(std::chrono::seconds(2)); } run = false; dqRead.stop(); dqWrite.stop(); std::this_thread::sleep_for(std::chrono::seconds(3)); std::cout << "main exit" << std::endl; return 0; }