Qt Toolkit - Thread Support in Qt

| Classes - Annotated - Tree - Functions - Home - Structure

# Thread Support in Qt

In version 2.2, Qt introduced thread support to Qt in the shape of some basic platform-independent threading classes, a thread-safe way of posting events and a global Qt library lock that allows you to call Qt methods from different threads.

## Preface

This document is intended for an audience that has knowledge and experience with multithreaded applications. Recommended reading:

- Threads Primer: A Guide to Multithreaded Programming
- Thread Time: The Multithreaded Programming Guide
- Pthreads Programming: A POSIX Standard for Better Multiprocessing (O'Reilly Nutshell)
- Win32 Multithreaded Programming

## Enabling thread support

When Qt is installed on Windows, thread support is an option on some compilers. The `mkfiles` subdirectory contains build files for various compilers - the ones with `-mt` in the name have thread support enabled.

On Unix, thread support is enabled by adding the `-thread` option when running the `configure` script. On Unix platforms where multithreaded programs must be linked in special ways, such as with a special libc, installation will create a separate library, `libqt-mt` and hence threaded programs must be linked against this library (with `-lqt-mt`) rather than the regular Qt library.

On both platforms, you should compile with the macro `QT_THREAD_SUPPORT` defined (eg. compile with `-DQT_THREAD_SUPPORT`). On Windows, this is usually done by an entry in `qconfig.h`.

## The Qt thread classes

The most important class, obviously, is QThread; this provides the means to start a new thread, which begins execution in your reimplementation of QThread::run(). This is similar to the Java thread class.

However, a thread class alone is not sufficient. In order to write threaded programs it is necessary to protect access to data that two threads wish to access at once. Therefore there is also a QMutex class; a thread can lock the mutex, and while it has it locked no other thread can lock the mutex; an attempt to do so will block the other thread until the mutex is released. For instance:

      class MyClass {
      public:
          void doStuff(int);

      private:
          QMutex mutex;
          int a;
          int b;
      };

      // This sets a to c, and b to c*2

      void MyClass::doStuff(int c)
      {
          mutex.lock();
          a=c;
          b=c*2;
          mutex.unlock();
      }

This ensures that only one thread at a time can be in MyClass::doStuff(), so b will always be equal to a*2.

Also necessary is a method for threads to wait for another thread to wake it up given a condition; the QWaitCondition class provides this. Threads wait for the QWaitCondition to indicate that something has happened, blocking until it does. When something happens, QWaitCondition can wake up all of the threads waiting for that event or one randomly selected thread (this is the same functionality as a POSIX Threads condition variable and is implemented as one on Unix). For instance:

      #include <qapplication.h>
      #include <qpushbutton.h>

      // global condition variable

      QWaitCondition mycond;

      // Worker class implementation

      class Worker : public QPushButton, public QThread
      {
      public:
          Worker(QWidget *parent = 0, const char *name = 0)
            : QPushButton(parent, name)
          {
              setText("Start Working");

              // connect the clicked() signal inherited from QPushButton to our
              // slotClicked() method
              connect(this, SIGNAL(clicked()), SLOT(slotClicked()));

              // call the start() method inherited from QThread... this starts
              // execution of the thread immediately
              QThread::start();
          }

      public slots:
          void slotClicked()
          {
              // wake up one thread waiting on this condition variable
              mycond.wakeOne();
          }

      protected:
          void run()
          {
              // this method is called by the newly created thread...

              while(1) {
                  // lock the application mutex, and set the caption of
                  // the window to indicate that we are waiting to
                  // start working
                  qApp->lock();
                  setCaption("Waiting");
                  qApp->unlock();

                   // wait until we are told to continue
                  mycond.wait();

                  // if we get here, we have been woken by another
                  // thread... let's set the caption to indicate
                  // that we are working
                  qApp->lock();
                  setCaption("Working!");
                  qApp->unlock();

                  // this could take a few seconds, minutes, hours, etc.
                  // since it is in a separate thread from the GUI thread
                  // the gui will not stop processing events...
                  do_complicated_thing();
              }
          }
      };

      // main thread - all GUI events are handled by this thread.

      main(int argc, char **argv)
      {
          QApplication app(argc, argv);

          // create a worker... the worker will run a thread when we do
          Worker firstworker(0, "worker");

          app.setMainWidget(&worker);
          worker.show();

          return app.exec();
      }

This program will wake up the worker thread whenever you press the button; the thread will go off and do some work and then go back to waiting to be told to do some more work. If the worker thread is already working when the button is pressed, nothing will happen. When the thread finishes working and calls QWaitCondition::wait() again, then it can be started.

## Thread-safe posting of events

In Qt, one thread is always the event thread - that is, the thread that pulls events from the window system and dispatches them to widgets. The static method QThread::postEvent posts events from threads other than the event thread. The event thread is woken up and the event delivered from within the event thread just as a normal window system event is. For instance, you could force a widget to repaint from a different thread by doing the following:

      QWidget *mywidget;
      QThread::postEvent( mywidget, new QPaintEvent( QRect(0, 0, 100, 100) ) );

This (asynchronously) makes mywidget to repaint a 100x100 square of its area.

## The Qt library mutex

The Qt library mutex provides a method for calling Qt methods from threads other than the event thread. For instance:

      QApplication *qApp;
      QWidget *mywidget;

      qApp->lock();

      mywidget->setGeometry(0,0,100,100);

      QPainter p;
      p.begin(mywidget);
      p.drawLine(0,0,100,100);
      p.end();

      qApp->unlock();

Calling a function in Qt without holding a mutex will generally result in unpredictable behavior. Calling a GUI-related function in Qt from a different thread requires holding the Qt library mutex. In this context, all functions that may ultimately access any graphics or window system resources are GUI-related. Using container classes, strings and I/O classes does not require any mutex if that object is only accessed by one thread.

## Caveats

Some things to watch out for when programming with threads:

- Don't do any blocking operations while holding the Qt library mutex. This will freeze up the event loop.
- Make sure you lock a recursive QMutex as many times as you unlock it, no more and no less.
- Lock the Qt application mutex before calling anything but the Qt container and tool classes.
- Be wary of classes which are implicitly shared; you should probably detach() them if you need to assign them between threads.
- Be wary of Qt classes which were not designed with thread safety in mind; for instance, QList's API is not thread-safe and if different threads need to iterate through a QList they should lock before calling QList::first() and unlock after reaching the end, rather than locking and unlocking around QList::next().
- Be sure to create objects that inherit or use QWidget, QTimer and QSocketNotifier objects only in the GUI thread. On some platforms, such objects created in a thread other than the GUI thread will never receive events from the underlying window system.
- Similar to the above, only use the QNetwork classes inside the GUI thread. A common question asked is if a QSocket can be used in multiple threads. This is unnecessary, since all of the QNetwork classes are asynchronous.
- Never call a function that attempts to processEvents from a thread that is not the GUI thread. This includes QDialog::exec(), QPopupMenu::exec(), QApplication::processEvents() and others.