The QThread anti-pattern

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.

2 thoughts on “The QThread anti-pattern

    1. 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

Comments are closed.