阻塞队列的QWaitCondition:在线程仍在等待时被销毁

4
我已经在Qt中建立了自己的阻塞队列,但目前存在一些问题。如果我不关闭队列,则会在控制台上出现错误 "QWaitCondition: Destroyed while threads are still waiting"。另一方面,如果我关闭队列(无论是在构造函数还是从其他线程中),则会出现访问冲突异常。异常发生在等待条件的wait方法中。
以下是我的阻塞队列:
#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中被唤醒时,互斥锁已经没有分配了,导致访问冲突异常。有什么最好的方法可以避免这种情况发生呢?

1个回答

0
我遇到的问题与线程处理有关,更多信息请查看此问题:为什么QThread :: finished信号没有被发出? 使用BlockingQueue的服务未正确关闭等待队列的线程,随后导致在线程仍在TryDequeue方法内等待时销毁队列。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接