逻辑很容易理解,直接看代码吧
#include <list>
#include <mutex>
#include <condition_variable>
#include <iostream>
#include <chrono>
#include <thread>
using namespace std;
template <typename T>
class CSyncQueue
{
public:
CSyncQueue(size_t size):
m_MaxQueue(size)
{
//条件变量和互斥所的成员变量由系统调用系统默认的构造
}
~CSyncQueue()
{
}
void push(T& t)
{
//该锁会在出作用域时,自己释放,不允许使用lock_guard,因为wait需要的锁类型是unique_lock
std::unique_lock<std::mutex> _(m_MutexQueue);
while (IsFull())
{
cout << "Queue is full,Please wait..." << endl;
m_CondNotFull.wait(_);
}
m_QueueNode.push_back(t);
//现在肯定有成员了,唤醒其中一个m_CondNotEmpty等待线程
m_CondNotEmpty.notify_all();
//唤醒所有m_CondNotEmpty等待线程
//m_CondNotEmpty.notify_all();
}
void pull(T& t)
{
std::unique_lock<std::mutex> _(m_MutexQueue);
while (IsEmpty())
{
cout << "Queue is empty,wait for a moment to pull." << en