When or how to delete QThread in Qt

multithreading, qt, windows

Solution

Your thread exits normally when its `worker` method execution completed, but if you want to do some things in thread exit time, use the `finished()` signal and it is possible to deallocate objects that live in thread that has just ended, by connecting the `finished()` signal to `QObject::deleteLater()`:

connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);

Problem

I found this QThread example from here. It recommends to use QObject and QThread over than subclassing QThread. ``` class Worker : public QObject { Q_OBJECT public slots: void doWork() { /* ... */ } }; QThread *thread = new QThread; Worker *worker = new Worker; worker->moveToThread(thread); thread->start(); QMetaObject::invokeMethod(worker, "doWork", Qt::QueuedConnection); ``` My first question is when and how to delete the thread? I have tried to connect finished to 2 slots, myTest and deleteLater. And I set a breakpoint in myTest, this never got triggered. So I suspect there is no finished signal, which mean the thread would not be deleted. ``` connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); connect(thread, SIGNAL(finished()), this, SLOT(myTest())); ``` For the worker object, I emit a finished signal as the last instruction in doWork, and connect it to a slot in which I can delete the worker object. Is this the right way? Qt version: 4.6.2

Original source

Related problems