Qt Signal Slot Thread Safe

This example was ported from the PyQt4 version by Guðjón Guðjónsson.

Qt provides thread support in the form of platform-independent threading classes, a thread-safe way of posting events, and signal-slot connections across threads. This makes it easy to develop portable multithreaded Qt applications and take advantage of multiprocessor machines. If you are moving your object through signals and slots (you have created your mpoller in one thread and called a signal and passed it to a slot of another object which is not in caller thread) make sure to use Qt::DirectConnection type for your connect. Qt - SigSlot - Boost Libraries Qt was the original signal/slots implementation, but it Sigslot and Boost on the other hand are pure ISO C, but both have some disadvantages. None of these are thread-safe and it can be somewhat inconvenient manually Qt documentation states that signals and slots can be direct, queued and auto. However, I think you can make the model use worker threads and then the model ensures that the correct signals are emitted, directly, and in the correct order. I think you would still have to use locks to ensure that a emailsRemoved signal from a worker thread doesn't get processed by the model until the correct time.

Qt Signal Slot Example

Introduction

In some applications it is often necessary to perform long-running tasks, such as computations or network operations, that cannot be broken up into smaller pieces and processed alongside normal application events. In such cases, we would like to be able to perform these tasks in a way that does not interfere with the normal running of the application, and ensure that the user interface continues to be updated. One way of achieving this is to perform these tasks in a separate thread to the main user interface thread, and only interact with it when we have results we need to display.

Qt signal thread

This example shows how to create a separate thread to perform a task - in this case, drawing stars for a picture - while continuing to run the main user interface thread. The worker thread draws each star onto its own individual image, and it passes each image back to the example's window which resides in the main application thread.

The User Interface

We begin by importing the modules we require. We need the math and random modules to help us draw stars.

The main window in this example is just a QWidget. We create a single Worker instance that we can reuse as required.

The user interface consists of a label, spin box and a push button that the user interacts with to configure the number of stars that the thread wil draw. The output from the thread is presented in a QLabel instance, viewer.

SlotSlot

We connect the standard finished() and terminated() signals from the thread to the same slot in the widget. This will reset the user interface when the thread stops running. The custom output(QRect, QImage) signal is connected to the addImage() slot so that we can update the viewer label every time a new star is drawn.

The start button's clicked() signal is connected to the makePicture() slot, which is responsible for starting the worker thread.

We place each of the widgets into a grid layout and set the window's title:

The makePicture() slot needs to do three things: disable the user interface widgets that are used to start a thread, clear the viewer label with a new pixmap, and start the thread with the appropriate parameters.

Since the start button is the only widget that can cause this slot to be invoked, we simply disable it before starting the thread, avoiding problems with re-entrancy.

We call a custom method in the Worker thread instance with the size of the viewer label and the number of stars, obtained from the spin box.

Whenever is star is drawn by the worker thread, it will emit a signal that is connected to the addImage() slot. This slot is called with a QRect value, indicating where the star should be placed in the pixmap held by the viewer label, and an image of the star itself:

We use a QPainter to draw the image at the appropriate place on the label's pixmap.

The updateUi() slot is called when a thread stops running. Since we usually want to let the user run the thread again, we reset the user interface to enable the start button to be pressed:

Now that we have seen how an instance of the Window class uses the worker thread, let us take a look at the thread's implementation.

The Worker Thread

The worker thread is implemented as a PyQt thread rather than a Python thread since we want to take advantage of the signals and slots mechanism to communicate with the main application.

We define size and stars attributes that store information about the work the thread is required to do, and we assign default values to them. The exiting attribute is used to tell the thread to stop processing.

Each star is drawn using a QPainterPath that we define in advance:

Before a Worker object is destroyed, we need to ensure that it stops processing. For this reason, we implement the following method in a way that indicates to the part of the object that performs the processing that it must stop, and waits until it does so.

For convenience, we define a method to set up the attributes required by the thread before starting it.

The start() method is a special method that sets up the thread and calls our implementation of the run() method. We provide the render() method instead of letting our own run() method take extra arguments because the run() method is called by PyQt itself with no arguments.

The run() method is where we perform the processing that occurs in the thread provided by the Worker instance:

Information stored as attributes in the instance determines the number of stars to be drawn and the area over which they will be distributed.

We draw the number of stars requested as long as the exiting attribute remains False. This additional check allows us to terminate the thread on demand by setting the exiting attribute to True at any time.

The drawing code is not particularly relevant to this example. We simply draw on an appropriately-sized transparent image.

For each star drawn, we send the main thread information about where it should be placed along with the star's image by emitting our custom output() signal:

Since QRect and QImage objects can be serialized for transmission via the signals and slots mechanism, they can be sent between threads in this way, making it convenient to use threads in a wide range of situations where built-in types are used.

Running the Example

We only need one more piece of code to complete the example:

The one thing that confuses the most people in the beginning is the Signal & Slot mechanism of Qt. But it’s actually not that difficult to understand. In general Signals & Slots are used to loosely connect classes. Illustrated by the keyword emit, Signals are used to broadcast a message to all connected Slots. If no Slots are connected, the message 'is lost in the wild'. So a connection between Signals & Slots is like a TCP/IP connection with a few exceptions, but this metaphor will help you to get the principle. A Signal is an outgoing port and a Slot is an input only port and a Signal can be connected to multiple Slots.

For me one of the best thins is, that you don’t have to bother with synchronization with different threads. For example you have one QObject that’s emitting the Signal and one QObject receiving the Signal via a Slot, but in a different thread. You connect them via QObject::connect(...) and the framework will deal with the synchronization for you. But there is one thing to keep in mind, if you have an object that uses implicitly sharing (like OpenCV’s cv::Mat) as parameter, you have to deal with the synchronization yourself.The standard use-case of Signals & Slots is interacting with the UI from the code while remaining responsive. This is nothing more than a specific version of 'communicating between threads'.Another benefit of using them is loosely coupled objects. The QObject emitting the Signal does not know the Slot-QObject and vice versa. This way you are able to connect QObjects that are otherwise only reachable via a full stack of pointer-calls (eg. this->objA->...->objZ->objB->recieveAQString()). Alone this can save you hours of work if someone decides to change some structure, eg. the UI.

Right now I only mentioned Signal- & Slot-methods. But you are not limited to methods - at least on the Slots side. You can use lambda functions and function pointers here. This moves some of the convenience from languages like Python or Swift to C++.

For some demonstrations I will use the following classes:

Using Connections

To connect a Signal to a Slot you can simply call QObject::connect(a, &AObject::signalSometing, b, &BObject::recieveAQString) or QObject::connect(a, SIGNAL(signalSometing(QString), b, SLOT(recieveAQString(QString)) if you want to use the 'old' syntax. The main difference is, if you use the new syntax, you have compile-time type-checking and -converting. But one big advantage of the 'old' method is that you don’t need to bother with inheritance and select the most specialized method.Lambdas can be a very efficient way of using Signals & Slots. If you just want to print the value, e.g. if the corresponding property changes, the most efficient way is to use lambdas. So by using lambdas you don’t have to blow up your classes with simple methods. But be aware, that if you manipulate any object inside the lambda you have to keep in mind, that synchronization issues (in a multithreaded environment) might occur.

Qt signal slot thread safe listSlot

You will get an idea of how to use the different methods in the following example:

As you see, recived a QString: 'Hello' is printed two times. This happens because we connected the same Signals & Slots two times (using different methods). In the case, you don’t want that, you see some methods to prohibit that and other options in the next section Connection Types.

One side note: if you are using Qt::QueuedConnection and your program looks like the following example, at some point you will probably wonder, why calling the Signal will not call the Slots until app.exec() is called. The reason for this behavior is that the event queue, the Slot-call is enqueued, will start with this call (and block until program exits).

And before we start with the next section here is a little trick to call a method of another thread inside the context of the other thread. This means, that the method will be executed by the other thread and not by the 'calling' one.

To learn more about that here is your source of truth: https://doc.qt.io/qt-5/qmetamethod.html#invoke

Connection Types

Qt::AutoConnection

Qt::AutoConnection is the default value for any QObject::connect(...) call. If both QObjects that are about to be connected are in the same thread, a Qt::DirectConnection is used. But if one is in another thread, a Qt::QueuedConnection is used instead to ensure thread-safety. Please keep in mind, if you have both QObjects in the same thread and connected them the connection type is Qt::DirectConnection, even if you move one QObject to another thread afterwards. I generally use Qt::QueuedConnection explicitly if I know that the QObjects are in different threads.

Qt::DirectConnection

A Qt::DirectConnection is the connection with the most minimal overhead you can get with Signals & Slots. You can visualize it that way: If you call the Signal the method generated by Qt for you calls all Slots in place and then returns.

Qt Signal Thread

Qt::QueuedConnection

The Qt::QueuedConnection will ensure that the Slot is called in the thread of the corresponding QObject. It uses the fact, that every thread in Qt (QThread) has a Event-queue by default. So if you call the Signal of the QObject the method generated by Qt will enqueue the command to call the Slot in the Event-queue of the other QObjects thread. The Signal-method returns immediately after enqueuing the command. To ensure all parameters exist within the other threads scope, they have to be copied. The meta-object system of Qt has to know all of the parameter types to be capable of that (see qRegisterMetaType).

Qt::BlockingQueuedConnection

Qt Signal Slot Performance

A Qt::BlockingQueuedConnection is like a Qt::QueuedConnection but the Signal-method will block until the Slot returns. If you use this connection type on QObjects that are in the same thread you will have a deadlock. And no one likes deadlocks (at least I don’t know anyone).

Qt::UniqueConnection

Qt::UniqueConnection is not really a connection type but a modifier. If you use this flag you are not able to connect the same connection again. But if you try it QObject::connect(...) will fail and return false.

This is not everything you will ever need to know about Signals & Slots but with this information you can cover about 80% of all use-cases (in my opinion).If it happens and you need the other 20% of information, I’ll give you some good links to search your specific problem on:

Qt Connect Signal Slot

The Qt documentation:

Very deep understanding:

Part1: https://woboq.com/blog/how-qt-signals-slots-work.html

Part2: https://woboq.com/blog/how-qt-signals-slots-work-part2-qt5.html

Part3: https://woboq.com/blog/how-qt-signals-slots-work-part3-queuedconnection.html

< previous step index next step >