并发编程中,数据产生和数据处理在不同的线程,这些线程传递数据常用的就是生产者消费者模式
以下是模仿Java的BlockingQueue实现的生产者消费者模式:
#pragma once
#include <queue>
#include <mutex>
#include <condition_variable>
enum PopResult{ POP_OK, POP_STOP, POP_UNEXPECTED };
template<class T>
class BlockingQueue : public std::queue<T>
{
public:
std::mutex m_lock;
std::condition_variable m_cond;
bool m_stopFlag = false;
virtual ~BlockingQueue() = default;
void push(const T& value)
{
std::lock_guard<decltype(m_lock)> lock(m_lock);
queue::push(value);
m_cond.notify_one();
}
void push(T&& value)
{
std::lock_guard<decltype(m_lock)> lock(m_lock);
queue::push(std::move(value));
m_cond.notify_one();
}
PopResult pop(T& out)
{
std::unique_lock<decltype(m_lock)> lock(m_lock);
if (m_stopFlag) // 停止
return POP_STOP;
if (empty())
m_cond.wait(lock);
if (m_stopFlag) // 停止
return POP_STOP;
if (empty()) // 意外唤醒?
return POP_UNEXPECTED;
out = std::move(front());
queue::pop();
return POP_OK;
}
void Stop()
{
std::lock_guard<decltype(m_lock)> lock(m_lock);
m_stopFlag = true;
m_cond.notify_all();
}
};
使用方法:
#include <iostream>
#include <thread>
BlockingQueue<int> g_queue;
// 生产者线程
void Produce()
{
for (int i = 0; i < 10; ++i)
g_queue.push(i);
}
// 消费者线程
void Consume()
{
int data;
while (true)
{
// 取数据
PopResult res = g_queue.pop(data);
if (res == POP_STOP) // 线程应该停止
break;
if (res == POP_UNEXPECTED) // 意外唤醒
continue;
// 处理数据
std::cout << data << std::endl;
}
}
int _tmain(int argc, _TCHAR* argv[])
{
// 启动生产者线程和消费者线程(也可以启动多个线程)
std::thread produceThread(Produce);
std::thread consumerThread(Consume);
// 等待数据处理完
Sleep(1000);
produceThread.join();
// 停止线程
g_queue.Stop();
consumerThread.join();
return 0;
}