Thread affinity and signal emission
-
Hi all
I'm confused on the topic of QObject's thread affinity and signal emission. I understand that when you connect to signal using QObject receiver, the slot will be called on receiver's thread. However it's not clear to me on which thread it will be called when receiver is not used (or connection is direct). Documentation says that "The slot is executed in the signalling thread." but which thread is that? Is that QObject::thread() of an object that emits the signal, or could it be some other thread in case object uses background worker thread internally?
I.e. with following hypothetical code:
auto* obj = new SomeObject{}; QObject::connect(obj, &SomeObject::someSignal, [obj] { assert(QThread::currentThread() == obj->thread()); });
Is it guaranteed that condition in lambda will be true for any SomeObject?
-
It's the actual thread the code is executed in.
-
As @Christian-Ehrlicher said: The slot is executed in the thread, where the receiver lives.
SinceQThread
inherits fromQObject
, you can simply assign a distinct object name to all your threads andqDebug() << __FUNCTION__ << QThread::currentThread()
in your slot (or lambda).That behavior can be asserted. A ui object e.g. is likely to crash, if modified from a different thread than the ui thread.