Qt thread slots and signals

Threads and QObjects

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, QFtp, 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 and the Blocking Fortune Client example.

Per-Thread Event Loop

Each thread can have its own event loop. The initial thread starts its event loops using QCoreApplication::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().

Note that for QObjects that are created before QApplication, QObject::thread() returns zero. This means that the main thread will only handle posted events for these objects; other event processing is not done at all for objects with no thread. Use the QObject::moveToThread() function to change 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:

    (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." 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. 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. 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.

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.

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.

2016 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.

Qt signal slot with threads

I have a problem with signal/slots in a QThread class. My design looks like this:

The signal never reaches my test() method. Can someone help? Thanks.

2 Answers 2

The problem is that sending signals

across threads results in queuing the signal into the target thread's event queue (a queued connection). If that thread never processes events, it'll never get the signal.

Returning from this method will end the execution of the thread.

In other words, having an empty run method results in instant termination of the thread, so you're sending a signal to a dead thread.

QThreads general usage

Threads in an operating system are a very simple thing. Write a function, maybe bundle it with some data and push it onto a newly created thread. Use a mutex or other method to safely communicate with the thread if necessary. Whether it are Win32, POSIX or other threads, they all basically work the same and are quite fool-proof.

Those who have discovered the joys of the Qt framework may assume that threads in Qt are just like this, and they would be right. However, there are several different ways to use threads in Qt, and it might not be obvious which approach to choose. The article, Multithreading Technologies in Qt, compares the different approaches.

The rest of this article demonstrates one of these methods: QThread + a worker QObject. This method is intended for use cases which involve event-driven programming and signals + slots across threads.

Usage with Worker class

The main thing in this example to keep in mind when using a QThread is that it's not a thread. It's a wrapper around a thread object. This wrapper provides the signals, slots and methods to easily use the thread object within a Qt project. To use it, prepare a QObject subclass with all your desired functionality in it. Then create a new QThread instance, push the QObject onto it using moveToThread(QThread*) of the QObject instance and call start() on the QThread instance. That's all. You set up the proper signal/slot connections to make it quit properly and such, and that's all.

Declare Worker class

For a basic example, check this class declaration for the Worker class:

We add at least one public slot which will be used to trigger the instance and make it start processing data once the thread has started. Now, let's see what the implementation for this basic class looks like.

While this Worker class doesn't do anything special, it nevertheless contains all the required elements. It starts processing when its main function, in this case process(), is called and when it is done it emits the signal finished() which will then be used to trigger the shutdown of the QThread instance it is contained in.

By the way, one extremely important thing to note here is that you should NEVER allocate heap objects (using new) in the constructor of the QObject class as this allocation is then performed on the main thread and not on the new QThread instance, meaning that the newly created object is then owned by the main thread and not the QThread instance. This will make your code fail to work. Instead, allocate such resources in the main function slot such as process() in this case as when that is called the object will be on the new thread instance and thus it will own the resource.

Create a new Worker instance

Now, let's see how to use this new construction by creating a new Worker instance and putting it on a QThread instance:

The connect() series here is the most crucial part. The first connect() line hooks up the error message signal from the worker to an error processing function in the main thread. The second connects the thread's started() signal to the processing() slot in the worker, causing it to start.

The most important features of Qt are signals and slots.

Signals tell you that something has just happened. Signals are emitted (sent) when the user works with the computer. For example, when the user clicks the mouse or presses keys on a keyboard a signal is emitted. Signals can also be emitted when something happens inside the computer—when the clock ticks, for example.

Slots are the functions that respond to certain signals. It is important that your program responds to signals. Otherwise, it might look as if your program hangs. KDE programs don't—or shouldn't—hang!

Signals and slots are very object independent. Slots that handle a signal can be put in any object in your program. The object that sends the signal doesn't have to know anything about the slot or the object where the slot can be found. For example, you may have one window that contains a button and one window that contains a text box. You can let the text box respond to button clicks.

Signals and slots are primarily used for events handling, but you can use it for easy communication between objects too. When two windows need to communicate with each other, you can use signals and slots. Communication this way is much easier than doing it with pointers.

Event handling is solved by callbacks in many other toolkits. A callback is a pointer to a function. The widgets contain callbacks, pointers to functions, for each event. When an event occurs, the appropriate function is called. It is simple in theory, but it is hard in practice. The callbacks are not type safe, which means that it is easy to make mistakes. Callbacks also can't take any number of parameters of any type like signals and slots do.

Creating a slot is easy. Any class that inherits from QObject can have slots.

First you must enable signals and slots. In the class definition, add the word Q OBJECT . This is a keyword, which the moc understands.

The slot is just a member function in your class, but you must declare it in a slots section. Slots can be public, private, or protected.

The following example shows a class with a slot:

The slot in the preceding class definition is called mySlot . The keyword before slots defines the access mode. The slot mySlot above is public.

You write the implementation for the slot as if it was a common member function. The following example shows you what a slot implementation may look like:

When you want to tell Qt that an event has occurred, you emit a signal. When that happens, Qt executes all slots that are connected to the signal.

Before a signal can be emitted, it must be defined. The class that emits a signal must contain the signal definition. Signals are defined in a signals section in your class. The following class definition defines a signal:

Signals are emitted with the command emit . The signal may be emitted like so:

1 2 // Constructor for MyWindow 3 MyWindow::MyWindow() : QWidget() 4 < 5 // Emit the signal created() 6 emit created(); 7 >8

The example above is only a simple demonstration that shows you how it works.

To make a slot respond to a certain signal, you must connect them to each other. You can connect several slots to one signal.

It is very simple to connect a slot to a signal. The command connect does this. The syntax is simple:

1 2 connect( startobject , SIGNAL( signal() ), targetobject , SLOT( slot() )) 3

The parameter startobject contains a pointer to the object that the signal comes from.

The parameter signal specifies what signal to handle. The signal must be emitted by the startobject .

The object which responds to a signal is specified in the parameter targetobject .

The slot which responds to the signal is specified in the parameter slot . The slot must be in the object specified by targetobject .

The following class demonstrates that several slots can be connected to the same signal, and one slot can be connected to several signals:

Example 3.4. buttons.h: Class Definition for the Class MyWindow

The listing below contains the class implementation:

Example 3.5. buttons.cc: Class Implementation for the Class MyWindow Declared in Listing 3.4

During communication, it is sometimes useful to say more than "Hey!" That is all that the preceding signals say.

If you need to say more, the simplest way is to use parameters in your signals and slots.

For example, you may have two windows both containing a button and a text box. When the user types in text and clicks the button in one window, the caption for the other window will change to whatever was typed in.

The solution is to use slots and signals with parameters. Give both the signal and slot a parameter that contains the new window caption. When you emit the signal you set this parameter.

The following example code shows how parameters work. The signal and slot are both in the same class, but of course that is not necessary:

The class constructor may connect the slot to the signal, like this:

The slot and the signal must have compatible parameters. In the preceding example, they each have one integer as a parameter.

It is easy to emit a signal with a parameter. The following function emits the signal changed(int i) :

1 2 void MyWindow::emitter(int i) 3 < 4 emit changed(i); 5 >6

When a signal is emitted, the slots connected to it are activated.

Take a look at the following class constructor:

A button is created. The clicked() signal is connected to temp-slotTemp() . When you delete temp , the slot slotTemp() is also deleted. If the user clicks the button, an error will occur. Always consider this when you delete Qt objects.

  • Qt signal slot main thread

    Qt signal slot main thread Threads and QObjects QThread inherits QObject. It emits signals to indicate that the thread started or finished executing, and...

  • Qt private slot vs public slot

    Does it make any difference, using public slots instead of private slots in Qt Does it make any difference, using public slots instead of private slots...

  • Play free wheel of fortune slot machine

    Wheel of Fortune Slot Machine If you are a fan of television shows, then you must know what Wheel of Fortune casino is all about. The project delivers...

  • Play real slots online win real money

    Play Las Vegas Slots Online For Real Money Play Las Vegas slots online for real money today! Two of the most popular Las Vegas slots that are popular...

  • Play free playson slot games

    Free Playson Slots and Casino Games Playson is a leading game developer that is well-known in the iGaming industry for consistently producing...