Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

emit and slots order execution

Tags:

signals

qt

One thread do an emit signal1();

A second thread do an emit signal2(); after that first thread has sent its signal ( there is the same mutex locked before emit call on both thread and I logged it, I can see in my log that first thread acquire lock before second thread)

first thread and second thread or not the GUI thread.

Is there any guarentees that signal1's slot will be call before signal2's slot ?

like image 658
Guillaume Paris Avatar asked Feb 19 '23 14:02

Guillaume Paris


1 Answers

As the emitter and the receiver objects are running in different threads, the slots will not be executed synchronously: Qt is using a queued connection by default instead of a direct connection. You can however force a synchronous execution by using a blocking queued connection (see also http://qt-project.org/doc/qt-4.8/qt.html#ConnectionType-enum for the description of the different connection types) when connecting signals and slots.

But a blocking queue connection has a cost: the emitter thread is blocked until all the connected slots are executed, which is not necessarily a good idea. If you want to use a non-blocking connection, however, the order of execution depends on the objects were the slots are executed.

The important thing to consider is that each QThread has its own event queue. It means that the order of execution is only guaranteed for the slots of a given thread. This means that you have to consider the following cases:

  • signal1's slot and signal2's slot are defined in QObject's living in the same thread: in that case, you can be sure that the slots are executed in the expected order because they are triggered by the same event queue
  • both slots are running in different threads: here you have no control over the order of execution as the signals are posted to 2 independent event queues. If this is the case, you have to use mutexes or wait conditions (or use a blocking connection).
like image 166
Benoit Avatar answered Mar 05 '23 03:03

Benoit