Good to know
Actually this is a nice example of race conditions:
Code:
:: Main thread ::
M01 connect(thread, SIGNAL(finished()), loop, SLOT(quit()), Qt::QueuedConnection);
M02 connect(timer, SIGNAL(timeout()), loop, SLOT(quit()));
M03
M04 while(thread->isRunning())
M05 {
M06 loop->exec();
M07 if(thread->isRunning())
M08 {
M09 qWarning("Potential deadlock in initialization thread!");
M10 }
M11 }
:: Worker thread ::
T01 DoActualWork();
T02
T03 [...]
T04
T05 emit thr->finished();
T06
T07 [...]
T08
T09 d->running = false;
T10 d->finished = true;
While the 'main' thread is waiting for the 'worker' thread to finish its job, it will be hanging in the Event Loop at M06.
Now it can happen that T05 gets executed in the 'worker' thread and then control switches to the 'main' thread
immediately, i.e. T09 and T10 have
not executed yet!
Consequently we will exit from M06, as the 'finished' signal just has been emitted - and that signal is connected to the 'quit' slot of the event loop.
However in M07 and M04 the "thread->isRunning()" expression will still evaluate to TRUE. That is because T09 and T10 have not "updated" the corresponding status flags yet
As the result, we will enter the wait loop once more! And, as the thread is not running anymore, only the "timeout" will
eventually help us the exit from the event loop...
(Note that the "Worker thread" code listed above is from the Qt Framework, so I cannot change that portion!)