Signal Slot Qt Thread

Qt documentation states that signals and slots can be direct, queued and auto. It also stated that if object that owns slot ‘lives’ in a thread different from object that owns signal, emitting such signal will be like posting message – signal emit will return instantly and slot method will be called in target thread’s event loop.

Qt::DirectConnection means that once the signal is generated, the slot function is executed immediately. (If the main thread sends a signal to the child thread, this parameter should use Qt::DirectConnection, and the slot function is executed immediately in the child thread) Qt::QueuedConnection. Take a look at Signals and slots across threads. If you always use signals and slots to communicate with the worker thread, Qt handles the moveToThread for you if it's needed and you used the correct connection.

As QAbstractItemView uses AutoConnections, the signals will be queued if they are in another thread. So, AFAIU, the model and view must be in the same thread if things are not to break. It's not impossible that a model would try to insert and remove rows in quick succession. In this case if you emit a signal from one thread, and catching it in another one (e.g. In main GUI thread) - Qt will put a slot's call to the message queue and will make all calls sequentially. Read this for further info - http://qt-project.org/doc/qt-4.8/threads-qobject.html#signals-and-slots-across-threads.

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

Slot

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.

Qt Signal Slot Thread

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.

Signal Slot Qt Thread Gages

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.

Signal Slot Qt Thread Dimensions

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.

Qt Signal Slot Thread Safe

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

Comments are closed.