I have a class WorkerThreadManager
that creates and owns a number of Qt threads:
class WorkerThread : public QThread
{
Q_OBJECT
public:
WorkerThread() : QThread()
{
start();
}
virtual ~SearchCacheWorkerThread()
{
quit();
wait();
}
virtual void run() Q_DECL_OVERRIDE
{
// fetch from mysql
// process results
// append many new items to results_
quit();
}
private:
QList<int> results_;
};
typedef QSharedPointer<WorkerThread> WorkerThreadPtr;
class WorkerThreadManager : QObject
{
Q_OBJECT
public:
WorkerThreadManager(const int numThreads) : QObject()
{
for ( int i = 0; i < numThreads; ++i )
{
threads_ << WorkerThreadPtr( new WorkerThread(), &QObject::deleteLater );
}
}
virtual ~WorkerThreadManager() {}
private:
QList<WorkerThreadPtr> threads_;
When I destroy the WorkerThreadManager
object, I don't see the memory being released.
I found from here that the deleteLater
won't do anything if the thread has exited the event loop. So I changed the code to remove all calls to quit()
in order to ensure a thread stays in the event loop until deleteLater is called. But I still get the memory leak.
- What's the correct way to destroy the threads (preferrably with the use of smart pointers)?
- How do I ensure that the threads will finish before they get destroyed, even if their destructor is called?