Qt Call Slot Thread

Posted on  by 



Qt - Passing custom objects among threads. Details Category: Programming Written by Nandan Banerjee Hits: 13021 Communication between threads in a qt program is essentially done by using signals/slots. This is by far one of the most easiest and stable mode of communication amongst threads of a program. 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 ConnectionThe slot is invoked immediately, when the signal is emitted. However, the connected slot function Syncro::jumpToFrame(int newframe) does not get called. If I change the connect from QueuedConnection to DirectConnection the slot function gets called but, as expected, in the context of my serviceThread. I need the slot function to run on the main thread. 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. Cross-thread signal-slot connections are implemented by dispatching a QMetaCallEvent to the target object. A QObject instance can be moved to a thread, where it will process its events, such as timer events or slot/method calls. To do work on a thread, first create your own worker class that derives from QObject. Then move it to the thread.

  1. Qt Call Slot Thread Reducer
  2. Qt Call Slot From Another 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 Call Slot Thread

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.

SlotCall

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.

Qt call slot thread reducer

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.

Qt - Passing custom objects among threads

Details
Category: Programming
Written by Nandan Banerjee
Hits: 13055

Communication between threads in a qt program is essentially done by using signals/slots. This is by far one of the most easiest and stable mode of communication amongst threads of a program.

For example, let us suppose that one thread needs to send an integer value to another thread. All the programmer needs to do is simply create a dispatch signal with two arguments, the thread id and the integer value. Thus, it can be achieved by this simple line –

Similarly, a receive slot with the same arguments needs to be created to receive the signal.

Now, this will work very nicely when one is dealing with the predefined primitive or the qt data types. This is because they are already registered and hence it is not a problem for qt to recognise those data types.

Qt Call Slot Thread Reducer

The problem arises when one wants to pass a custom data type (any class or structure that has a public default constructor, a public copy constructor, and a public destructor can be registered). Then, the user defined class or a class defined in a library not part of qt can be passed using signals/slots after registering.

The qRegisterMetaType() function is used to make the type available to non-template based functions, like the queued signal and slot connections.

This is done in the following way –

where name can be any custom data type.

For example, let us take a program which will capture the image from the webcam and display it in a QLabel on the GUI. To achieve this, two approaches can be taken. Run the camera grabbing function in the main UI thread or in a different thread and reducing the work of the UI thread significantly. If it is run in the main UI thread, then the chances of the UI thread not responding is very high. Therefore, it is always desirable make a separate thread and use it instead to run the camera grabbing function.

Qt Call Slot From Another Thread

In this tutorial, we will use the openCV library to grab an image from the webcam and use the signal/slot mechanism to send the image (IplImage type) to the UI thread.

After creating a new qtGUI project, a new class is created (say “webcamThread”) with QThread as its parent class. A run() function is defined and a new signal with the image as the argument is defined.

In the MainWindow file, a slot is defined to handle the signal from the webcamThread. This image is then converted to the QImage format and then displayed in the QLabel. So, a smooth and pleasant webcam feed can be achieved using this.

Qt code for the webcam feed -

The openCV library needs to be present in the system and the paths should be appropriately set.

// webcamthread.h

// webcamthread.cpp

Now the code for the MainWindow. The signals are connected with the slots and the event handlers are defined.

// mainwindow.h

// mainwindow.cpp

In the UI editor, two buttons (Start and Stop) and a label of size 320 by 240 need to be created. Then, just compile and run. So, it can be seen that objects of the class “IplImage” from the openCV library can be easily passed between the threads just by registering the class.





Coments are closed