Qt Signal Slot Event Loop



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

As of Qt4, you can use QThread to start your own event loops. This might sound somewhat uninteresting at first, but it means you can have your own signals and slots outside the main thread. The Trolls created a new way to connect signals to slots such that signals can actually cross thread boundaries. I can now emit a signal in one thread.

9.3.3 Signals and Slots When the main thread of a C program calls qApp-exec , it enters into an event loop, where messages are handled and dispatched. While qApp is executing its event loop, it is possible for QObject s to send messages to one another. Exercise 13: Qt Signals and Slots¶ GitHub Invitation URL: exercise13. Steps: Clone the assignment for today after accepting the GitHub invitation at the link above. The repository contains four files: trafficlight.h defines a Qt widget that uses three radio buttons to simulate a traffic light. Trafficlight.cpp is the implementation of the. Like with a QueuedConnection, an event is posted to the other thread's event loop. A pointer to a QSemaphore. The thread that delivers the event will release the semaphore right after the slot has been called. Meanwhile, the thread that called the signal will acquire the semaphore in order to wait until the event is processed. The QEventLoop basically manage Qt events into the main loop and work as the exec function of a QDialog class that doesn't return until the close function is called (the QDialog itself use this class internally).

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.

Qt signal slot event loop tool

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.

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.

Accessing QObject Subclasses from Other Threads

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.

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.

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.

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.

Qt signal slot event loop tutorial

© 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

Qt Signals And Slots Without Event Loop

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:

Qt Signal Slot Event Loop

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 Signal Slot Event Loop C++

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.

SignalSlotDirectQueued
const Copy&const Copy&01
const Copy&Copy12
Copyconst Copy&12
CopyCopy23

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.