I have two classes – one that runs in the main thread and performs GUI operations and another that performs some calculations and makes network requests.
// A member of the class that runs in the main thread
QThread thread;
Here is a snippet from the initialization method of the class that runs in the main thread:
// Create the class that runs in the other thread and move it there
CServerThread * server = new CServerThread;
server->moveToThread(&thread);
// When the thread terminates, we want the object destroyed
connect(&thread, SIGNAL(finished()), server, SLOT(deleteLater()));
thread.start();
In the destructor for the class that runs in the main thread:
if(thread.isRunning())
{
thread.quit();
thread.wait();
}
What I expect to happen is the thread terminates and destroys the instance of the CServerThread class. However, the destructor for the CServerThread class is not getting invoked.
QThread::quit()stops the event loop for that thread.But
QObject::deleteLater()needs the event loop for the “owning” thread to be active:So your object’s destructor will not run, the
finishedsignal is fired too late for that.Consider the contrived example below:
If you call:
The output will be:
finishedis triggered after thewaitis done. Too late for yourdeleteLaterconnection to be effective, that thread’s event loop is already dead.