Qt Signal Slot Different Thread
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:
Re: Connecting signals & slots across different threads See: Thread support in Qt Although QObject is reentrant, the GUI classes, notably QWidget and all its subclasses, are not reentrant. When one QObject instance is the receiver of a signal, its thread affinity is checked, and by default the signal is delivered directly as a function call when is the same thread affinity of the sender. But if the thread affinity differs, it will be delivered posting an event to the object.
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.
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::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
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:
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 >
Home > Articles > Programming > C/C++
␡- Creating Threads
This chapter is from the book
This chapter is from the book
14. Multithreading
- Creating Threads
- Synchronizing Threads
- Communicating with the Main Thread
- Using Qt's Classes in Secondary Threads
Conventional GUI applications have one thread of execution and perform one operation at a time. If the user invokes a time-consuming operation from the user interface, the interface typically freezes while the operation is in progress. Chapter 7 presents some solutions to this problem. Multithreading is another solution.
In a multithreaded application, the GUI runs in its own thread and additional processing takes place in one or more other threads. This results in applications that have responsive GUIs even during intensive processing. When runnning on a single processor, multithreaded applications may run slower than a single-threaded equivalent due to the overhead of having multiple threads. But on multiprocessor systems, which are becoming increasingly common, multithreaded applications can execute several threads simultaneously on different processors, resulting in better overall performance.
In this chapter, we will start by showing how to subclass QThread and how to use QMutex, QSemaphore, and QWaitCondition to synchronize threads. [*] Then we will see how to communicate with the main thread from secondary threads while the event loop is running. Finally, we round off with a review of which Qt classes can be used in secondary threads and which cannot.
Multithreading is a large topic with many books devoted to the subject—for example, Threads Primer: A Guide to Multithreaded Programming by Bil Lewis and Daniel J. Berg (Prentice Hall, 1995) and Multithreaded, Parallel, and Distributed Programming by Gregory Andrews (Addison-Wesley, 2000). Here it is assumed that you already understand the fundamentals of multithreaded programming, so the focus is on explaining how to develop multithreaded Qt applications rather than on the subject of threading itself.
Creating Threads
Providing multiple threads in a Qt application is straightforward: We just subclass QThread and reimplement its run() function. To show how this works, we will start by reviewing the code for a very simple QThread subclass that repeatedly prints a given string on a console. The application's user interface is shown in Figure 14.1.
Qt Connect Signal Slot
Figure 14.1 The Threads application
The Thread class is derived from QThread and reimplements the run() function. It provides two additional functions: setMessage() and stop().
The stopped variable is declared volatile because it is accessed from different threads and we want to be sure that it is freshly read every time it is needed. If we omitted the volatile keyword, the compiler might optimize access to the variable, possibly leading to incorrect results.
We set stopped to false in the constructor.
The run() function is called to start executing the thread. As long as the stopped variable is false, the function keeps printing the given message to the console. The thread terminates when control leaves the run() function.
The stop() function sets the stopped variable to true, thereby telling run() to stop printing text to the console. This function can be called from any thread at any time. For the purposes of this example, we assume that assignment to a bool is an atomic operation. This is a reasonable assumption, considering that a bool can have only two states. We will see later in this section how to use QMutex to guarantee that assigning to a variable is an atomic operation.
Qt Signal Slot Thread Performance
QThread provides a terminate() function that terminates the execution of a thread while it is still running. Using terminate() is not recommended, since it can stop the thread at any point and does not give the thread any chance to clean up after itself. It is always safer to use a stopped variable and a stop() function as we did here.
We will now see how to use the Thread class in a small Qt application that uses two threads, A and B, in addition to the main thread.
The ThreadDialog class declares two variables of type Thread and some buttons to provide a basic user interface.
In the constructor, we call setMessage() to make the first thread repeatedly print 'A's and the second thread 'B's.
When the user clicks the button for thread A, startOrStopThreadA() stops the thread if it was running and starts it otherwise. It also updates the button's text.
The code for startOrStopThreadB() is structurally identical.
If the user clicks Quit or closes the window, we stop any running threads and wait for them to finish (using QThread::wait()) before we call QCloseEvent::accept(). This ensures that the application exits in a clean state, although it doesn't really matter in this example.
If you run the application and click Start A, the console will be filled with 'A's. If you click Start B, it will now fill with alternating sequences of 'A's and 'B's. Click Stop A, and now it will print only 'B's.
Related Resources
- Book $31.99
- eBook (Watermarked) $25.59
Qt Signal Slot Different Thread Gages
- eBook (Watermarked) $28.79