c++multithreadingqt

Qt: How to clean up a QThread when you do not subclass it?


If I have the most standard code of using a QThread like this:

myClass* object = new myClass();
QThread* worker = new QThread();
object->moveToThread(worker);
worker->start();

Then what is the proper way to delete object and the proper way to quit the worker thread?

If I don't delete object there will be memory leakage.

If I don't quit worker, when I close the application, there will be warning said that QThread is destroyed while it is still running.


Solution

  • To delete your object object, you can connect the QThread::finished signal of your worker object to the QObject::deleteLater slot of your object object.

    And to quit your thread, you can call QThread::quit and QThread::wait in the destructor of your class (or whenever you need to stop your thread).

    MyClass::~MyClass()
    {
        thread->quit();
        thread->wait();
        ...
    }
    

    To delete your worker object, you can just set a parent to it, or make it an automatic member variable. You can also use a smart pointer for it.

    By the way, your naming convention is a bit odd. The QThread object in your case is not a worker, it just manages the thread. The myClass object would be the worker in your case.