Home | All Classes | Main Classes | Annotated | Grouped Classes | Functions |

# Thread Support in Qt

Qt provides thread support in the form of 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.

This document is intended for people who have knowledge and experience of creating multithreaded applications. If you don't have this knowledge, here is some suggested reading to get you started:

- 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

Warning: All GUI classes (e.g. QWidget and subclasses), OS kernel classes (e.g. QProcess), and networking classes, are not thread-safe.

QRegExp uses a static cache and is not threadsafe at all, even if the QRegExp object is protected by using QMutex.

## Enabling Thread Support

When Qt is installed on Windows, thread support is an option on some compilers.

On Mac OS X and 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 standard Qt library.

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

## The Thread Classes

The most important class 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.

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 example:

        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 `c * 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 example:

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

        // global condition variable
        QWaitCondition mycond;

        // Worker class implementation
        class Worker : public QPushButton, public QThread
        {
            Q_OBJECT

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

                for ( ;; ) {
                    // 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.
        int 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 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 example:

      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. You must hold the Qt library mutex before calling a GUI-related function from a different thread. 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 except for the Qt container and tool classes.

- Be wary of implicitly shared classes; you should avoid copying them with operator=() between threads. There are plans to improve this in a future Qt release.

- Be wary of Qt classes which were not designed with thread safety in mind; for instance, QPtrList's API is not thread-safe and if different threads need to iterate through a QPtrList they should lock before calling QPtrList::first() and unlock after reaching the end, rather than locking and unlocking around QPtrList::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 other than the GUI thread. This includes QDialog::exec(), QPopupMenu::exec(), QApplication::processEvents() and others.

- Don't mix the normal Qt library and the threaded Qt library in your application. This means that if your application uses the threaded Qt library, you should not link with the normal Qt library, dynamically load the normal Qt library or dynamically load another library or plugin that depends on the normal Qt library. On some systems, doing this can corrupt the static data used in the Qt library.