Search code examples
c++qtqthread

QThread finished state


QThread * thread = new QThread();
qDebug() << "Finished: " << thread->isFinished();

Console is:

Finished: 0

The thread was never started, should not isFinished() returns true (1) instead of false (0) ?

NB: isRunning returns 0 and it is correct.


Solution

  • No. The finished state is there to indicate that before that quit() or exit() have been called. It is an alternative to receiving the finished() signal.

    The quit() and exit() lead to run() (which is the only part of the thread that actually runs in a separate thread) returning to the thread that your QThread instance belongs to. After that a cleanup procedure is executed - events beside the designated deletion ones can no longer be processed.

    The finished state is triggered and you can safely remove the instance of your QThread. finished() signal is emitted (in most cases connected to deleteLater() slots of the objects that reside in the separate thread) and isFinished() returns true.

    Naturally if you haven't started the thread it cannot be finished because it never ran. :D Joke aside, it is perfectly safe to remove an instance of QThread that hasn't been started at all.

    If you are more interested in this I suggest you look at the source code of QThread to see how the class is sturctured and its implementation works.