Qt Call Slot From Different Thread
While the purpose of threads is to allow code to run in parallel, there are times where threads must stop and wait for other threads. For example, if two threads try to write to the same variable simultaneously, the result is undefined. The principle of forcing threads to wait for one another is called mutual exclusion. It is a common technique for protecting shared resources such as data.
Qt's event systemis very useful for inter-thread communication. Every thread may have its own event loop. To call a slot (or any invokablemethod) in another thread, place that call in the target thread's event loop. The event loops of Qt are a very valuable tool for inter-thread communication. Every thread may have its own event loop. A safe way of calling a slot in another thread is by placing that call in another thread's event loop. This ensures that the target object finishes the method that is currently running before another method is started. Here's Qt 5's new way to connect two QObjects and pass non-string objects: connect( sender, &Sender::valueChanged, receiver, &Receiver::updateValue ); Pros. Compile time check of the existence of the signals and slot, of the types, or if the QOBJECT is missing. Argument can be by typedefs or with different namespace specifier, and it works.
Qt provides low-level primitives as well as high-level mechanisms for synchronizing threads.
Low-Level Synchronization Primitives
QMutex is the basic class for enforcing mutual exclusion. A thread locks a mutex in order to gain access to a shared resource. If a second thread tries to lock the mutex while it is already locked, the second thread will be put to sleep until the first thread completes its task and unlocks the mutex.
QReadWriteLock is similar to QMutex, except that it distinguishes between 'read' and 'write' access. When a piece of data is not being written to, it is safe for multiple threads to read from it simultaneously. A QMutex forces multiple readers to take turns to read shared data, but a QReadWriteLock allows simultaneous reading, thus improving parallelism.
QSemaphore is a generalization of QMutex that protects a certain number of identical resources. In contrast, a QMutex protects exactly one resource. The Semaphores Example shows a typical application of semaphores: synchronizing access to a circular buffer between a producer and a consumer.
QWaitCondition synchronizes threads not by enforcing mutual exclusion but by providing a condition variable. While the other primitives make threads wait until a resource is unlocked, QWaitCondition makes threads wait until a particular condition has been met. To allow the waiting threads to proceed, call wakeOne() to wake one randomly selected thread or wakeAll() to wake them all simultaneously. The Wait Conditions Example shows how to solve the producer-consumer problem using QWaitCondition instead of QSemaphore.
Note: Qt's synchronization classes rely on the use of properly aligned pointers. For instance, you cannot use packed classes with MSVC.
These synchronization classes can be used to make a method thread safe. However, doing so incurs a performance penalty, which is why most Qt methods are not made thread safe.
Risks
If a thread locks a resource but does not unlock it, the application may freeze because the resource will become permanently unavailable to other threads. This can happen, for example, if an exception is thrown and forces the current function to return without releasing its lock.
Another similar scenario is a deadlock. For example, suppose that thread A is waiting for thread B to unlock a resource. If thread B is also waiting for thread A to unlock a different resource, then both threads will end up waiting forever, so the application will freeze.
Convenience classes
QMutexLocker, QReadLocker and QWriteLocker are convenience classes that make it easier to use QMutex and QReadWriteLock. They lock a resource when they are constructed, and automatically unlock it when they are destroyed. They are designed to simplify code that use QMutex and QReadWriteLock, thus reducing the chances that a resource becomes permanently locked by accident.
High-Level Event Queues
Qt's event system is very useful for inter-thread communication. Every thread may have its own event loop. To call a slot (or any invokable method) in another thread, place that call in the target thread's event loop. This lets the target thread finish its current task before the slot starts running, while the original thread continues running in parallel.
To place an invocation in an event loop, make a queued signal-slot connection. Whenever the signal is emitted, its arguments will be recorded by the event system. The thread that the signal receiver lives in will then run the slot. Alternatively, call QMetaObject::invokeMethod() to achieve the same effect without signals. In both cases, a queued connection must be used because a direct connection bypasses the event system and runs the method immediately in the current thread.
There is no risk of deadlocks when using the event system for thread synchronization, unlike using low-level primitives. However, the event system does not enforce mutual exclusion. If invokable methods access shared data, they must still be protected with low-level primitives.
Having said that, Qt's event system, along with implicitly shared data structures, offers an alternative to traditional thread locking. If signals and slots are used exclusively and no variables are shared between threads, a multithreaded program can do without low-level primitives altogether.
See also QThread::exec() and Threads and QObjects.
© 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.
How often is a an object copied, if it is emitted by a signal as a const reference and received by a slot as a const reference? How does the behaviour differ for direct and queued signal-slot connections? What changes if we emit the object by value or receive it by value?
Nearly every customer asks this question at some point in a project. The Qt documentation doesn’t say a word about it. There is a good discussion on stackoverflow, which unfortunately leaves it to the reader to pick the right answer from all the answers and comments. So, let’s have a systematic and detailed look at how arguments are passed to signals and slots.
Setting the Stage
For our experiments, we need a copyable class that we will pass by const reference or by value to signals and slots. The class – let’s call it Copy
– looks as follows.
The copy constructor and the assignment operator simply perform a member-wise copy – like the compiler generated versions would do. We implement them explicitly to set breakpoints or to print debugging messages. The default constructor is only required for queued connections. We’ll learn the reason later.
We need another class, MainView
, which ultimately derives from QObject
. MainView provides the following signals and slots.
MainView
provides four signal-slot connections for each connection type.
The above code is used for direct connections. For queued connections, we comment out the first line and uncomment the second and third line.
The code for emitting the signals looks as follows:
Direct Connections
sendConstRef => receiveConstRef
We best set breakpoints in the copy constructor and assignment operator of the Copy
class. If our program only calls emit sendConstRef(c)
, the breakpoints are not hit at all. So, no copies happen. Why?
The result is not really surprising, because this is exactly how passing arguments as const references in C++ works and because a direct signal-slot connection is nothing else but a chain of synchronous or direct C++ function calls.
Nevertheless, it is instructive to look at the chain of function calls executed when the sendConstRef
signal is emitted.
The meta-object code of steps 2, 3 and 4 – for marshalling the arguments of a signal, routing the emitted signal to the connected slots and de-marshalling the arguments for the slot, respectively – is written in such a way that no copying of the arguments occurs. This leaves us with two places, where copying of a Copy
object could potentially occur: when passing the Copy
object to the functions MainView::sendConstRef
or MainView::receiveConstRef
.
These two places are governed by standard C++ behaviour. Copying is not needed, because both functions take their arguments as const references. There are also no life-time issues for the Copy
object, because receiveConstRef
returns before the Copy
object goes out of scope at the end of sendConstRef
.
sendConstRef => receiveValue
Based on the detailed analysis in the last section, we can easily figure out that only one copy is needed in this scenario. When qt_static_meta_call
calls receiveValue(Copy c)
in step 4, the original Copy
object is passed by value and hence must be copied.
sendValue => receiveConstRef
One copy happens, when the Copy
object is passed by value to sendValue
by value.
sendValue => receiveValue
This is the worst case. Two copies happen, one when the Copy
object is passed to sendValue
by value and another one when the Copy
object is passed to receiveValue
by value.
Queued Connections
A queued signal-slot connection is nothing else but an asynchronous function call. Conceptually, the routing function QMetaObject::activate
does not call the slot directly any more, but creates a command object from the slot and its arguments and inserts this command object into the event queue. When it is the command object’s turn, the dispatcher of the event loop will remove the command object from the queue and execute it by calling the slot.
When QMetaObject::activate
creates the command object, it stores a copy of the Copy
object in the command object. Therefore, we have one extra copy for every signal-slot combination.
We must register the Copy
class with Qt’s meta-object system with the command qRegisterMetaType('Copy');
in order to make the routing of QMetaObject::activate
work. Any meta type is required to have a public default constructor, copy constructor and destructor. That’s why Copy
has a default constructor.
Queued connections do not only work for situations where the sender of the signal and the receiver of the signal are in the same thread, but also when the sender and receiver are in different threads. Even in a multi-threaded scenario, we should pass arguments to signals and slots by const reference to avoid unnecessary copying of the arguments. Qt makes sure that the arguments are copied before they cross any thread boundaries.
Qt Call Slot From Different Thread Type
Conclusion
The following table summarises our results. The first line, for example, reads as follows: If the program passes the argument by const reference to the signal and also by const reference to the slot, there are no copies for a direct connection and one copy for a queued connection.
Signal | Slot | Direct | Queued |
---|---|---|---|
const Copy& | const Copy& | 0 | 1 |
const Copy& | Copy | 1 | 2 |
Copy | const Copy& | 1 | 2 |
Copy | Copy | 2 | 3 |
Qt Call Slot From Different Threads
The conclusion from the above results is that we should pass arguments to signals and slots by const reference and not by value. This advice is true for both direct and queued connections. Even if the sender of the signal and the receiver of the slot are in different threads, we should still pass arguments by const reference. Qt takes care of copying the arguments, before they cross the thread boundaries – and everything is fine.
By the way, it doesn’t matter whether we specify the argument in a connect call as const Copy&
or Copy
. Qt normalises the type to Copy
any way. This normalisation does not imply, however, that arguments of signals and slots are always copied – no matter whether they are passed by const reference or by value.