#include "Repository.h"
#include <QDebug>
Repository::Repository()
{
m_nQueue_Max_Size = 10; //默认最大长度为10,可根据需求修改
}
void Repository::AddData(QString str)
{
std::unique_lock<std::mutex> lock(m_Queue_Mutex);
//判断是否队列满
while (m_queue.count() > m_nQueue_Max_Size)
{
//等待信号触发,阻塞在此处。此时会释放m_Queue_Mutex锁,
//其他线程可以获取m_Queue_Mutex
qDebug() << "queue is full";
m_Queue_Not_Full.wait(lock);
}
m_queue.enqueue(str);
qDebug() << QString("add [%1]").arg(str);
m_Queue_Not_Empty.notify_all();
lock.unlock(); //释放锁,也可以不调用,最后函数返回时也会释放
}
QString Repository::TakeData()
{
std::unique_lock<std::mutex> lock(m_Queue_Mutex);
//判断是否队列满
while (m_queue.isEmpty())
{
//等待信号触发,阻塞在此处。此时会释放m_Queue_Mutex锁,
//其他线程可以获取m_Queue_Mutex
qDebug() << "queue is empty";
m_Queue_Not_Empty.wait(lock);
}
QString str = m_queue.dequeue(); //获取数据
qDebug() << QString("get [%1]").arg(str);
m_Queue_Not_Full.notify_all();
lock.unlock(); //释放锁,也可以不调用,最后函数返回时也会释放
return str;
}