ConcurrentQueue
用C++11提供的多线程类实现一个线程安全的队列:
#include <queue>
#include <mutex>
#include <condition_variable>
#include <utility>
template<typename T, typename Queue = std::queue<T>>
class ConcurrentQueue {
public:
template<typename U>
void push(U&& elem) {
{
std::lock_guard<std::mutex> guard(m_mutex);
m_queue.push(std::forward<U>(elem));
}
m_cv.notify_one();
}
T pop() {
std::unique_lock<std::mutex> lock(m_mutex);
m_cv.wait(lock, [this] { return !m_queue.empty(); });
auto elem = std::move(m_queue.front());
m_queue.pop();
return elem;
}
private:
std::mutex m_mutex;
std::condition_variable m_cv;
Queue m_queue;
};