Qt offers many classes and functions for working with threads. Below are four different approaches that Qt programmers can use to implement multithreaded applications.

QThread: Low-Level API with Optional Event Loops

QThread is the foundation of all thread control in Qt. Each QThread instance represents and controls one thread.

What Qt spec says about thread-affinity: timers started in one thread, cannot be stopped from another thread. And only the thread owning a socket instance can use this socket. This implies that you must stop any running timers in the thread that started them and you must call QTcpSocket::close in the thread owning the socket. However there is a lot of communication necessary between the two threads, mostly the GUI sending commands to the Skype thread to do things (call, answer, send message, log in, etc). So far to send a command I just can just create a signal in the GUI class, like 'doCall' which gets hooked up to the 'call' slot in the Skype thread.

QThread can either be instantiated directly or subclassed. Instantiating a QThread provides a parallel event loop, allowing QObject slots to be invoked in a secondary thread. Subclassing a QThread allows the application to initialize the new thread before starting its event loop, or to run parallel code without an event loop.

See the QThread class reference and the threading examples for demonstrations on how to use QThread.

QThreadPool and QRunnable: Reusing Threads

Creating and destroying threads frequently can be expensive. To reduce this overhead, existing threads can be reused for new tasks. QThreadPool is a collection of reuseable QThreads.

To run code in one of a QThreadPool's threads, reimplement QRunnable::run() and instantiate the subclassed QRunnable. Use QThreadPool::start() to put the QRunnable in the QThreadPool's run queue. When a thread becomes available, the code within QRunnable::run() will execute in that thread.

Each Qt application has a global thread pool, which is accessible through QThreadPool::globalInstance(). This global thread pool automatically maintains an optimal number of threads based on the number of cores in the CPU. However, a separate QThreadPool can be created and managed explicitly.

Qt Concurrent: Using a High-level API

The Qt Concurrent module provides high-level functions that deal with some common parallel computation patterns: map, filter, and reduce. Unlike using QThread and QRunnable, these functions never require the use of low-level threading primitives such as mutexes or semaphores. Instead, they return a QFuture object which can be used to retrieve the functions' results when they are ready. QFuture can also be used to query computation progress and to pause/resume/cancel the computation. For convenience, QFutureWatcher enables interactions with QFutures via signals and slots.

Qt Concurrent's map, filter and reduce algorithms automatically distribute computation across all available processor cores, so applications written today will continue to scale when deployed later on a system with more cores.

This module also provides the QtConcurrent::run() function, which can run any function in another thread. However, QtConcurrent::run() only supports a subset of features available to the map, filter and reduce functions. The QFuture can be used to retrieve the function's return value and to check if the thread is running. However, a call to QtConcurrent::run() uses one thread only, cannot be paused/resumed/canceled, and cannot be queried for progress.

See the Qt Concurrent module documentation for details on the individual functions.

WorkerScript: Threading in QML

The WorkerScript QML type lets JavaScript code run in parallel with the GUI thread.

Each WorkerScript instance can have one .js script attached to it. When WorkerScript.sendMessage() is called, the script will run in a separate thread (and a separate QML context). When the script finishes running, it can send a reply back to the GUI thread which will invoke the WorkerScript.onMessage() signal handler.

Using a WorkerScript is similar to using a worker QObject that has been moved to another thread. Data is transferred between threads via signals.

See the WorkerScript documentation for details on how to implement the script, and for a list of data types that can be passed between threads.

Choosing an Appropriate Approach

As demonstrated above, Qt provides different solutions for developing threaded applications. The right solution for a given application depends on the purpose of the new thread and the thread's lifetime. Below is a comparison of Qt's threading technologies, followed by recommended solutions for some example use cases.

Comparison of Solutions

FeatureQThreadQRunnable and QThreadPoolQtConcurrent::run()Qt Concurrent (Map, Filter, Reduce)WorkerScript
LanguageC++C++C++C++QML
Thread priority can be specifiedYesYes
Thread can run an event loopYes
Thread can receive data updates through signalsYes (received by a worker QObject)Yes (received by WorkerScript)
Thread can be controlled using signalsYes (received by QThread)Yes (received by QFutureWatcher)
Thread can be monitored through a QFuturePartiallyYes
Built-in ability to pause/resume/cancelYes

Example Use Cases

Lifetime of threadOperationSolution
One callRun a new linear function within another thread, optionally with progress updates during the run.Qt provides different solutions:
  • Place the function in a reimplementation of QThread::run() and start the QThread. Emit signals to update progress. OR
  • Place the function in a reimplementation of QRunnable::run() and add the QRunnable to a QThreadPool. Write to a thread-safe variable to update progress. OR
  • Run the function using QtConcurrent::run(). Write to a thread-safe variable to update progress.
One callRun an existing function within another thread and get its return value.Run the function using QtConcurrent::run(). Have a QFutureWatcher emit the finished() signal when the function has returned, and call QFutureWatcher::result() to get the function's return value.
One callPerform an operation on all items of a container, using all available cores. For example, producing thumbnails from a list of images.Use Qt Concurrent's QtConcurrent::filter() function to select container elements, and the QtConcurrent::map() function to apply an operation to each element. To fold the output into a single result, use QtConcurrent::filteredReduced() and QtConcurrent::mappedReduced() instead.
One call/PermanentPerfrom a long computation in a pure QML application, and update the GUI when the results are ready.Place the computation code in a .js script and attach it to a WorkerScript instance. Call WorkerScript.sendMessage() to start the computation in a new thread. Let the script call sendMessage() too, to pass the result back to the GUI thread. Handle the result in onMessage and update the GUI there.
PermanentHave an object living in another thread that can perform different tasks upon request and/or can receive new data to work with.Subclass a QObject to create a worker. Instantiate this worker object and a QThread. Move the worker to the new thread. Send commands or data to the worker object over queued signal-slot connections.
PermanentRepeatedly perform an expensive operation in another thread, where the thread does not need to receive any signals or events.Write the infinite loop directly within a reimplementation of QThread::run(). Start the thread without an event loop. Let the thread emit signals to send data back to the GUI thread.

© 2020 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.

QThread inherits QObject. It emits signals to indicate that the thread started or finished executing, and provides a few slots as well.

More interesting is that QObjects can be used in multiple threads, emit signals that invoke slots in other threads, and post events to objects that 'live' in other threads. This is possible because each thread is allowed to have its own event loop.

QObject Reentrancy

QObject is reentrant. Most of its non-GUI subclasses, such as QTimer, QTcpSocket, QUdpSocket and QProcess, are also reentrant, making it possible to use these classes from multiple threads simultaneously. Note that these classes are designed to be created and used from within a single thread; creating an object in one thread and calling its functions from another thread is not guaranteed to work. There are three constraints to be aware of:

  • The child of a QObject must always be created in the thread where the parent was created. This implies, among other things, that you should never pass the QThread object (this) as the parent of an object created in the thread (since the QThread object itself was created in another thread).
  • Event driven objects may only be used in a single thread. Specifically, this applies to the timer mechanism and the network module. For example, you cannot start a timer or connect a socket in a thread that is not the object's thread.
  • You must ensure that all objects created in a thread are deleted before you delete the QThread. This can be done easily by creating the objects on the stack in your run() implementation.

Although QObject is reentrant, the GUI classes, notably QWidget and all its subclasses, are not reentrant. They can only be used from the main thread. As noted earlier, QCoreApplication::exec() must also be called from that thread.

In practice, the impossibility of using GUI classes in other threads than the main thread can easily be worked around by putting time-consuming operations in a separate worker thread and displaying the results on screen in the main thread when the worker thread is finished. This is the approach used for implementing the Mandelbrot Example and the Blocking Fortune Client Example.

Slot

In general, creating QObjects before the QApplication is not supported and can lead to weird crashes on exit, depending on the platform. This means static instances of QObject are also not supported. A properly structured single or multi-threaded application should make the QApplication be the first created, and last destroyed QObject.

Per-Thread Event Loop

Each thread can have its own event loop. The initial thread starts its event loop using QCoreApplication::exec(), or for single-dialog GUI applications, sometimes QDialog::exec(). Other threads can start an event loop using QThread::exec(). Like QCoreApplication, QThread provides an exit(int) function and a quit() slot.

An event loop in a thread makes it possible for the thread to use certain non-GUI Qt classes that require the presence of an event loop (such as QTimer, QTcpSocket, and QProcess). It also makes it possible to connect signals from any threads to slots of a specific thread. This is explained in more detail in the Signals and Slots Across Threads section below.

A QObject instance is said to live in the thread in which it is created. Events to that object are dispatched by that thread's event loop. The thread in which a QObject lives is available using QObject::thread().

The QObject::moveToThread() function changes the thread affinity for an object and its children (the object cannot be moved if it has a parent).

Calling delete on a QObject from a thread other than the one that owns the object (or accessing the object in other ways) is unsafe, unless you guarantee that the object isn't processing events at that moment. Use QObject::deleteLater() instead, and a DeferredDelete event will be posted, which the event loop of the object's thread will eventually pick up. By default, the thread that owns a QObject is the thread that creates the QObject, but not after QObject::moveToThread() has been called.

If no event loop is running, events won't be delivered to the object. For example, if you create a QTimer object in a thread but never call exec(), the QTimer will never emit its timeout() signal. Calling deleteLater() won't work either. (These restrictions apply to the main thread as well.)

You can manually post events to any object in any thread at any time using the thread-safe function QCoreApplication::postEvent(). The events will automatically be dispatched by the event loop of the thread where the object was created.

Event filters are supported in all threads, with the restriction that the monitoring object must live in the same thread as the monitored object. Similarly, QCoreApplication::sendEvent() (unlike postEvent()) can only be used to dispatch events to objects living in the thread from which the function is called.

Qt Call Slot In Different Thread

Accessing QObject Subclasses from Other Threads

Qt Invoke Method Another Thread

QObject and all of its subclasses are not thread-safe. This includes the entire event delivery system. It is important to keep in mind that the event loop may be delivering events to your QObject subclass while you are accessing the object from another thread.

If you are calling a function on an QObject subclass that doesn't live in the current thread and the object might receive events, you must protect all access to your QObject subclass's internal data with a mutex; otherwise, you may experience crashes or other undesired behavior.

Like other objects, QThread objects live in the thread where the object was created -- not in the thread that is created when QThread::run() is called. It is generally unsafe to provide slots in your QThread subclass, unless you protect the member variables with a mutex.

On the other hand, you can safely emit signals from your QThread::run() implementation, because signal emission is thread-safe.

Qt Invoke Slot Another Thread Set

Signals and Slots Across Threads

Qt supports these signal-slot connection types:

  • Auto Connection (default) If the signal is emitted in the thread which the receiving object has affinity then the behavior is the same as the Direct Connection. Otherwise, the behavior is the same as the Queued Connection.'
  • Direct Connection The slot is invoked immediately, when the signal is emitted. The slot is executed in the emitter's thread, which is not necessarily the receiver's thread.
  • Queued Connection The slot is invoked when control returns to the event loop of the receiver's thread. The slot is executed in the receiver's thread.
  • Blocking Queued Connection The slot is invoked as for the Queued Connection, except the current thread blocks until the slot returns.

    Note: Using this type to connect objects in the same thread will cause deadlock.

  • Unique Connection The behavior is the same as the Auto Connection, but the connection is made only if it does not duplicate an existing connection. i.e., if the same signal is already connected to the same slot for the same pair of objects, then the connection is not made and connect() returns false.

Qt Invoke Slot Another Thread Holder

The connection type can be specified by passing an additional argument to connect(). Be aware that using direct connections when the sender and receiver live in different threads is unsafe if an event loop is running in the receiver's thread, for the same reason that calling any function on an object living in another thread is unsafe.

Holder

QObject::connect() itself is thread-safe.

The Mandelbrot Example uses a queued connection to communicate between a worker thread and the main thread. To avoid freezing the main thread's event loop (and, as a consequence, the application's user interface), all the Mandelbrot fractal computation is done in a separate worker thread. The thread emits a signal when it is done rendering the fractal.

Similarly, the Blocking Fortune Client Example uses a separate thread for communicating with a TCP server asynchronously.

© 2020 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.