[英]BlockingQueue's QWaitCondition: Destroyed while threads are still waiting
我在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
喚醒線程時,不再分配互斥鎖,因此會導致訪問沖突異常。 避免這種情況的最佳方法是什么?
我遇到的問題與線程方法有關,更多信息請看這個問題: 為什么沒有發出QThread :: finished信號?
使用BlockingQueue
的服務沒有正確關閉正在隊列中等待的線程,並且當線程仍然在TryDequeue
方法內等待時,它隨后導致隊列被銷毀。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.