很多情況下要用到生產者-消費者這個模型,比如有很多任務要處理,但是又不能馬上得到處理,這個時候就難免要將任務緩存下來慢慢消化。最普通的就是一對一的模式,一個生產者,一個消費者。那麼有幾個點需要考慮:
- 生產速度大於消費速度,這個時候就需要隊列的支持,需要把任務緩存下來慢慢消化
- 勻速消化,保證任務執行之間的間隔時間相同,很多情況下我們是有這個要求的,比如有一堆繪製任務,不能無節制的全部交給屏幕繪製,可能會阻塞主線程,這個時候就要給主線程留出交互的空隙。
- 如果生產速度遠遠大於消費速度,我們就需要設置隊列最大長度,保護我們的程序。
- 任務丟棄策略,如果任務超出隊列,如何丟棄(暫不考慮這個問題)
#include <functional>
#include <memory>
#include <thread>
#include <queue>
#include <condition_variable>
template<typename T>
class ConsumeQueue
{
typedef std::function<void(T)> ConsumeFunction;
public:
//consumeRate: 消耗速率(消息個數/1s)
ConsumeQueue(int consumeRate, int publishQueueMaxSize = 1000);
~ConsumeQueue() { Stop(); };
void Publish(T data);
void Consume(ConsumeFunction consumeFunction);
void Stop();
void SetConsumeRate(int rate);
int GetConsumeRate();
int GetPublishQueueLength();
private:
void ConsumeThreadFunction(ConsumeFunction consumeFunction);
private:
std::thread* m_thread = nullptr;
//生產者隊列
std::queue<T> m_publishQueue;
int m_consumeRate;
int m_publishQueueMaxSize;
std::condition_variable m_wait;
std::mutex m_mut;
bool m_isStop = false;
};
template<typename T>
int ConsumeQueue<T>::GetPublishQueueLength()
{
return m_publishQueue.size();
}
template<typename T>
int ConsumeQueue<T>::GetConsumeRate()
{
return m_consumeRate;
}
template<typename T>
void ConsumeQueue<T>::SetConsumeRate(int rate)
{
if (m_consumeRate == rate)
{
return;
}
m_consumeRate = rate;
}
template<typename T>
void ConsumeQueue<T>::Stop()
{
{
std::unique_lock<std::mutex> locker(m_mut);
m_isStop = true;
m_wait.notify_all();
}
if (m_thread)
{
m_thread->join();
delete m_thread;
m_thread = nullptr;
}
}
template<typename T>
void ConsumeQueue<T>::Publish(T data)
{
if (m_isStop)
{
return;
}
std::unique_lock<std::mutex> locker(m_mut);
m_publishQueue.push(data);
if (m_publishQueue.size() > m_publishQueueMaxSize)
{
m_publishQueue.pop();
}
m_wait.notify_all();
}
template<typename T>
void ConsumeQueue<T>::Consume(ConsumeFunction consumeFunction)
{
m_thread = new std::thread([=]() {
ConsumeThreadFunction(consumeFunction);
});
}
template<typename T>
ConsumeQueue<T>::ConsumeQueue(int consumeRate, int publishQueueMaxSize)
{
m_consumeRate = consumeRate;
m_publishQueueMaxSize = publishQueueMaxSize;
}
template<typename T>
void ConsumeQueue<T>::ConsumeThreadFunction(ConsumeFunction consumeFunction)
{
while (!m_isStop)
{
std::unique_lock<std::mutex> locker(m_mut);
if (m_publishQueue.empty())
{
m_wait.wait(locker);
}
if (m_isStop)
{
return;
}
std::queue<T> consumeQueue;
consumeQueue.swap(m_publishQueue);
locker.unlock();
while (!consumeQueue.empty() && !m_isStop)
{
consumeFunction(consumeQueue.front());
consumeQueue.pop();
std::this_thread::sleep_for(std::chrono::milliseconds(1000 / m_consumeRate));
}
}
}
Publish是生產接口,將任務加入到隊列中,可以是函數對象,也可以是string,int等等
Consume接受一個lambda或者一個函數,這個是消費接口,也就是會將數據在這裏吐出,可以在這個函數中對數據處理,但是需要注意,Consume接口是在另外一個線程中執行的,注意目的,ui繪製的操作不能放在這裏。
構造函數中的兩個參數: consumeRate是指1秒鐘要消費任務的個數,publishQueueMaxSize是指緩存隊列的最大長度,超出會將新消息加入,並將最早的消息丟棄掉。