我不知道我的代码到底有什么问题,它从不使队列出队,而是 isEmpty 总是满足 true。
class ConcurrentQueue
{
private:
QQueue<QByteArray> dataStore;
public:
void Enqueue(QByteArray value);
QByteArray Dequeue();
bool isEmpty();
private:
QMutex mutex;
};
void ConcurrentQueue::Enqueue(QByteArray value)
{
qDebug() << dataStore.length();
mutex.lock();
dataStore.enqueue(value);
mutex.unlock();
qDebug() << dataStore.length();
}
QByteArray ConcurrentQueue::Dequeue()
{
// mutex.lock();
// return dataStore.dequeue();
// mutex.unlock();
QByteArray tmp;
mutex.lock();
if(!dataStore.isEmpty())
{
tmp = dataStore.dequeue();
}
mutex.unlock();
return tmp;
}
bool ConcurrentQueue::isEmpty()
{
return dataStore.isEmpty();
}
接下来,一个计时器连接到一个插槽,以每隔 10 毫秒将一个数据包排入队列:
QByteArray built((char*)data, len) ;
//qDebug() << built.toHex();
qDebug() << "EnQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ";
queue.Enqueue(built);
一个线程定期检查此队列是否为空,它将队列出列并执行某些操作,但 isEmplty 始终返回 true
if(queue.isEmpty())
{
qDebug() << "#####################################";
return;
}
//NEVER COMES HERE
QByteArray rd15Bytes = queue.Dequeue();
这是线程:
Write::Write()
{
}
void Write::run(){
while(1)
{
rs.writeToSerialPort(); // in this function above always isemplty is true
this->msleep(10);
}
}