Queues with the maximum length limit through the condition ﹣ variable:
#include <condition_variable> #include <queue> #include <chrono> #include <iostream> /* * There is a maximum number of queues limit */ // parameter T Need to be able to copy,And the copy doesn't have side effects template <typename T> class sync_queue { public: sync_queue(int queueMaxSize): m_queueMaxSize(queueMaxSize) { } // Processing data threads template <typename Func> typename std::result_of<Func(T)>::type readQueue(Func readFunc) { T data; // Remove data, Then process the data { std::unique_lock<std::mutex> lock(m_queueMtx); m_consumeCv.wait(lock, [this]{ return m_data.size() != 0; }); data = m_data.front(); m_data.pop(); } m_produceCv.notify_one(); return readFunc(data); } // Production data thread, The return value indicates whether the production is successful or not,If it's timed out, it won't succeed template <typename Rep, typename Period> bool writeQueue(T data, const std::chrono::duration<Rep, Period>& wait_time) { // Preset a consumer to process this data { std::unique_lock<std::mutex> lock(m_queueMtx); auto success = m_produceCv.wait_for(lock, wait_time, [this]{ return m_data.size() <= m_queueMaxSize; }); if (!success) { return false; } m_data.push(std::move(data)); } m_consumeCv.notify_one(); return true; } private: // Used to store values stored by producers std::queue<T> m_data; // Used to represent data to be processed int m_queueMaxSize; // For queue protection std::mutex m_queueMtx; // Used to remind you that you can consume now std::condition_variable m_consumeCv; // Used to remind the current production std::condition_variable m_produceCv; };
Because of the need to control the length of the queue, there is no secondary cache. That is to say, there is no secondary cache such as std::vector in the consuming thread. The problem of uniform distribution needs to be considered when using the secondary cache. Of course, even if the secondary cache is used, the length of the data to be processed can also be controlled, but the processing will become very complex. Here is just a simple use Method, need other effect, can refer to build