Search code examples
c++multithreadingqtqthread

Multi-threads cause the runtime error in Qt


When I am trying to do multi-threads in Qt, for example:
If I create a class object in another class like this:

QThread thread;
Worker worker;
worker.moveToThread(thread);

it will cause the runtime error when I close the program.

But if I create the class object by pointer like this:

QThread* thread = new QThread;
Worker* worker = new Worker();
worker->moveToThread(thread);

it will be no error. Why do I have to do like this?

And do I have to delete the pointer after using? If I do not, will that cause the memory leak? I see a lot of tutorials delete them like this:

connect(worker, SIGNAL (finished()), thread, SLOT (quit()));
connect(worker, SIGNAL (finished()), worker, SLOT (deleteLater()));
connect(thread, SIGNAL (finished()), thread, SLOT (deleteLater()));

Solution

  • Qt typically manages the memory of its objects. Lots of the documentation says this, but not all of it.

    Your runtime error is caused by a double-delete. In the first example, when worker goes out of scope it will be destructed, and Qt will also attempt to delete it. In the second example, only Qt deletes it, and you do not.

    If you look towards Qt's own documentation of this, you can see them doing the same thing:

    Controller() {
        Worker *worker = new Worker;
        worker->moveToThread(&workerThread);
       ...
    } // notice worker was not cleaned up here, which implies moveToThread takes ownership
    

    However, moveToThread's documentation isn't clear on this.