Reputation: 69958
Suppose 2 QThread
s are running with following relation:
connect(&Object1OfThread1, &Object1::Signal,
&Object2OfThread2, &Object2::Slot, Qt::QueuedConnection);
So when an object from one thread raises a signal, the other thread's slot is invoked. As discussed in Qt signals (QueuedConnection and DirectConnection), due to Qt::QueuedConnection
, the Signal()
is posted/appended into the event loop of the Thread2. When it turn comes, the Slot()
is invoked.
Question: Is the event loop itself thread-safe?
viz. what if Thread1 and Thread3 both post a signal simultaneously to Thread2's event loop.
Upvotes: 1
Views: 1166
Reputation: 22890
Qt event loop is thread safe but not atomic.
Thread safety
As long as Object2OfThread2
state is always modified by the thread associated with Thread2
, there won't be any race conditions. At most one slot will be executed at any time.
Atomicity
The order of execution of slots is governed by :
So I would not advise to assume a specific order of execution for a given slot.
what if Thread1 and Thread3 both post a signal simultaneously to Thread2's event loop
Object2OfThread2
even if they are "posted" simultaneously.Object2OfThread2, &Object2::Slot
, they will be processed before being posted on Object2OfThread2
event loop. If the signals emitted simultaneously, Thread3 signal will be the first queued, so the first to execute. Upvotes: 2
Reputation: 69958
The article mentioned in this comment, says that the event queue is protected by a mutex.
How Qt Signals and Slots Work - Part 3 - Queued and Inter Thread Connections
A
QueuedConnection
will post an event to the event loop to eventually be handled.When posting an event (in
QCoreApplication::postEvent
), the event will be pushed in a per-thread queue (QThreadData::postEventList
). The event queue is protected by a mutex, so there is no race conditions when threads push events to another thread's event queue.Once the event has been added to the queue, and if the receiver is living in another thread, we notify the event dispatcher of that thread by calling
QAbstractEventDispatcher::wakeUp
. This will wake up the dispatcher if it was sleeping while waiting for more events. If the receiver is in the same thread, the event will be processed later, as the event loop iterates.
Upvotes: 2