Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct
Managing QThread/worker cleanup on destructor
rom1v last edited by
The first exemple on this page "this page":http://doc.qt.io/qt-5/qthread.html#details embed an object QThread in a class Controller. Therefore, it is forced to call wait() in ~Controller, else the QThread object would be destroyed too early.
On the same documentation page, some § later:
Note: wait() and the sleep() functions should be unnecessary in general, since Qt is an event-driven framework. Instead of wait(), consider listening for the finished() signal.
I totally agree with that. If I use a thread, this is probably because I don't want to freeze the UI. Calling a wait() in the ~Controller() could freeze, so IMO it is a very bad idea. Therefore, I think it is better to use a QThread* in Controller instead, and to connect &QThread::finished to &QObject::deleteLater for both the worker and the workerThread.
That way, the controller destructor can complete without waiting, and the worker/workerThread will be deleted when possible. And that works fine…
Except on program termination. If the controller destructor is called due to program termination, then the event loop is stopping, so the deleteLater slots would never be called. We may say "we don't care, the program terminates", but it seems deficient; in theory, we could still want to execute the worker/workerThread destructors at the end of the program (and it would avoid valgrind to report a lot of memory leaks).
What do you think?