Talking to Qt Threads

I wrote about multi-threading in Qt a while back, and how to use QThread to wrap a blocking function call “lock free”. Today we’ll talk about how to pass data into your thread. This approach can be used, for example, to tell your QThread to stop.

There are two ways to use QThread, with and without an event loop, and the preferred method for talking to a QThread depends on which of them you use.

Way 1: Without an event loop

When you’re not using an event loop, the thread’s run() method often looks like this:

void MyThread::run()
{
    forever
    {
        // Do some stuff
    }
}

Since this method does not use an event loop, there is no way to deliver a signal to your thread. So if you want to pass data into the thread, you have to use a good old fashioned mutex. Let’s look at an example showing you how to stop your thread:

void MyThread::run()
{
    forever
    {
        {
            // "mutex" and "stopRequested" are member
            // variables of MyThread:
            QMutexLocker locker(&mutex);
            if(stopRequested)
                return;
        }
        
        // Do some stuff
    }
}

void MyThread::stop()
{
    QMutexLocker locker(&mutex);
    stopRequested = true;
}

In this case, we have to check the stopRequested variable in a timely manner in our thread’s run() method. The longer you run between checks, the longer it will take your thread to actually stop.

Outside observers can use the finished() signal to know when your thread is actually done. So if you are in a QMainWindow, for example, and a closeEvent() happens, you can ignore the event, call MyThread::stop(), and then when the QThread::finished() signal arrives, you can actually close the window.

The downside is that the stop() call will actually block while it tries to acquire the mutex. Given the way this code is written, the blocking will probably be very short, but hey, I hate blocking. Let’s see if we can dig up a better way to do this.

Way 2: With an event loop

If you have an event loop, you can use Qt’s meta-objects to talk to your thread. Let’s look at the same example as before, only this time with no locking or blocking.

void MyThread::MyThread()
{
    moveToThread(this);
}

void MyThread::run()
{
    QTimer *timer = new QTimer();
    connect(timer, SIGNAL(timeout()),
        this, SLOT(doSomething()));
    timer->start(0);

    exec(); // starts the event loop, and doesn't
            // return until it is told to quit()
}

void MyThread::stop()
{
    if(currentThread() != this)
    {
        // The caller is running in a
        // different thread, so use Qt to
        // call stop() later, on our own thread:
        QMetaObject::invokeMethod(this, "stop",
                        Qt::QueuedConnection);
    }
    else
    {
        // Now the call has arrived from our
        // own thread, yay! We can safely
        // shut down our event loop.
        quit();
    }
}

Look mom! No locks! Now we have killed our thread, safely and gracefully. There is no chance of blocking, and we learned something about QMetaObject.

A couple items to note:

  • The doSomething() method is left as an exercise for the reader, but be careful about the QTimer interval. I used 0, which means it will be firing almost constantly.
  • The stop() method must be a slot in MyThread (and not just a regular method) or else invokeMethod() will return false and not actually re-invoke stop() for you.
  • You can pass arguments to your thread this way, but it requires a bit more fun with QMetaObject::invokeMethod().
  • You can reduce this whole thing to a magical macro that you could put at the top of your stop() method, saving you from having to write if(currentThread() == this) at the top of every method. Hint: use the __FUNCTION__ macro.
  • To run this example code, you’ll need to #include these files: QThread, QTimer, QMetaObject, QMutexLocker, and QMutex
  • To call quit(), it may not actually be necessary to be running on the same QThread (it works for me without the QMetaObject), but this will be required when you start passing in data to your thread. Without it, your program could do unpredictable naughty things. I can’t find anything in the docs about whether quit() is thread safe.

I’ve found this QMetaObject approach the most effective and easiest way to pass data to QThreads safely, without blocking and without locks.

Happy threading!

Write a Reply or Comment

Your email address will not be published.