BlockingQueue QWaitCondition: Destroyed while threads are still waiting

I built my own blocking queue in Qt and I was having a little problem. If I do not close the queue, then I get an error message in the console " QWaitCondition: Destroyed while threads are still waiting ". On the other hand, I get an access violation exception after closing the queue (regardless of whether it is in the constructor or another thread). An exception occurs in standby standby standby.

Here is my blocking queue:

 #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 

I assume this is because the thread waiting for the message after the queue has already been destroyed, and the mutex will also be destroyed. When a thread wakes up in TryDequeue , the mutex is no longer allocated, so it throws an access violation exception. What is the best way to avoid this?

+4
source share
1 answer

The problem that I encountered was related to the approach to the thread, for more information, consider this question: Why QThread :: the finished signal is not emitted?

A service using BlockingQueue n’t close the thread waiting for the queue and subsequently caused the queue to be destroyed while the thread is still inside the TryDequeue method.

0
source

Source: https://habr.com/ru/post/1446549/


All Articles