Sometimes with QThread you see something like this:
void run()
{
while (true) {
{
QMutexLocker lock(&mMutexData);
if (mQuit)
break;
}
msleep (200);
}
mWaitExit.wakeAll();
}
void stop()
{
mMutexData.lock();
mQuit = true;
mMutexData.unlock();
mWaitExit.wait(&mMutexExit);
}
This is potentially problematic. Why? Consider the extreme case of a function shutdown()
which does something like this:
void shutdown()
{
thread->stop();
delete thread;
}
Congratulations, you’ve just introduced a race condition. Why, you will ask? You’re waiting for the thread to end before deleting it, right?
No. And this has to do with the way Qt implements QThread::wait()
which you should have probably used in the first place, if you really need this sort of functionality.
Qt hooks a pthread cleanup handler in the native thread which will call wakeAll()
on a QWaitCondition
stored inside the pimpl of QThread
. And this pimpl – you might have guessed – is gone when you call delete
.
Are you sure you want to derive from QThread? See this: http://labs.qt.nokia.com/2010/06/17/youre-doing-it-wrong
Yes, I know that one – nevertheless you see the thing I mentioned quite often; that post was about what is out there, not how it should be