我在 Qt 中建立了自己的阻塞队列,但遇到了一些问题。如果我不关闭队列,则会在控制台“ QWaitCondition: Destroyed while threads are still waiting
”中收到错误消息。另一方面,我在关闭队列后遇到访问冲突异常(无论它是在构造函数中还是来自另一个线程)。异常发生在等待条件的等待方法中。
这是我的阻塞队列:
#ifndef BLOCKING_QUEUE_H
#define BLOCKING_QUEUE_H
#include <QObject>
#include <QSharedPointer>
#include <QWaitCondition>
#include <QMutex>
#include <queue>
namespace Concurrency
{
template<typename Data>
class BlockingQueue
{
private:
QMutex _mutex;
QWaitCondition _monitor;
volatile bool _closed;
std::queue<QSharedPointer<Data>> _queue;
public:
BlockingQueue()
{
_closed = false;
}
~BlockingQueue()
{
Close(); // When this is enabled, I get an access violation exception in TryDequeue
}
void Close()
{
QMutexLocker locker(&_mutex);
if(!_closed)
{
_closed = true;
_queue.empty();
_monitor.wakeAll();
}
}
bool Enqueue(QSharedPointer<Data> data)
{
QMutexLocker locker(&_mutex);
// Make sure that the queue is not closed
if(_closed)
{
return false;
}
_queue.push(data);
// Signal all the waiting threads
if(_queue.size()==1)
{
_monitor.wakeAll();
}
return true;
}
bool TryDequeue(QSharedPointer<Data>& value, unsigned long time = ULONG_MAX)
{
QMutexLocker locker(&_mutex);
// Block until something goes into the queue
// or until the queue is closed
while(_queue.empty())
{
if(_closed || !_monitor.wait(&_mutex, time)) // <-- Access violation if I call close in the destructor
{
return false;
}
}
// Dequeue the next item from the queue
value = _queue.front();
_queue.pop();
return true;
}
};
}
#endif BLOCKING_QUEUE_H
我假设正在发生这种情况,因为在队列已经被销毁并且互斥体随后也被销毁之后,正在等待的线程得到了信号。当线程在 中唤醒时TryDequeue
,不再分配互斥锁,因此会导致访问冲突异常。避免这种情况的最佳方法是什么?