单独队列,由于多线程访问的锁冲突较大,采取双缓冲队列来解决锁的冲突,生产者线程不断的向write queue写入数据,当read queue队列中无数据时,进行数据的交换;交换完成之后,生产者线程向交换完成之后的write queue继续写入数据,消费者从read queue队列读取数据。
#include <queue>
#include <mutex>
#include <condition_variable>
template<class T>
class MessageRWQueue {
public:
void push(T& msg)
{
std::unique_lock<std::mutex> lock(m_swapMutex);
m_writeQueue.emplace(msg);
m_cond.notify_one();
}
bool po11(T& msg)
{
if (m_readQueue.empty())
{
std::unique_lock<std::mutex> lock(m_swapMutex);
if (m_writeQueue.empty())
{
return false;
}
m_readQueue.swap(m_writeQueue);
}
msg = m_readQueue.front();
m_readQueue.pop();
return true;
}
void wait(T& msg)
{
if (m_readQueue.empty())
{
std::unique_lock<std::mutex> lock(m_swapMutex);
if (m_writeQueue.empty())
{
m_cond.wait(lock);
}
m_readQueue.swap(m_writeQueue);
}
msg = m_readQueue.front();
m_readQueue.pop();
}
private:
std::queue<T> m_writeQueue;
std::queue<T> m_readQueue;
std::mutex m_swapMutex;
std::condition_variable m_cond;
};