5

In my code I emit a signal mySignal and I want to wait for the end of a connected slot mySlot execution before it continues:

emit mySignal();
// Wait for the end of mySlot execution...

// Some code that has to be executed only after the end of mySlot execution...

Is there a way to do so ?

Laurent Mesguen
  • 354
  • 2
  • 6
  • 22
  • 4
    Do the signal and connected slot belong to objects in the same thread? If so, this will happen anyway. If not, the Qt approach is not to wait, but to emit another signal at the end of the connected slot, which causes the remainder of the code to run. – bnaecker Feb 01 '17 at 16:49
  • 1
    You're probably better off with a standard callback function in these types of cases rather than invoking the overhead of Qt's signals and slots. – MrEricSir Feb 01 '17 at 16:51

1 Answers1

10

If the sender and the receiver are in the same thread use Qt::DirectConnection, if they are in 2 different threads use Qt::BlockingQueuedConnection.

ClassA a;
ClassB b;
ClassC c;
c.moveToThread(aThread);
QObject::connect(&a, &ClassA::signal, &b, &ClassB::slot, Qt::DirectConnection);
QObject::connect(&a, &ClassA::signal, &c, &ClassC::slot, Qt::BlockingQueuedConnection);

Please note that you will have to disconnect/reconnect if:

  • the sender and the receiver end up the the same thread and they previously were not,or you will have a dead lock.
  • the sender or the receiver end up in 2 different threads and they previously were in the same thread.

Also Qt::DirectConnection is the default if the sender and receiver are in the same thread (see Qt::AutoConnection).

Benjamin T
  • 8,120
  • 20
  • 37
  • I have a single threaded App, which is used for socket read write. Whenever the data is received on socket, in the same function data is written for ACK. However, it seems that many a times the data received in between when the slot is still getting executed. The function is not yet completed and this leads to a recursive hierarchy which crashes later on. Is there any solution for this? – iammilind Oct 04 '17 at 14:19
  • 1
    @iammilind You should ask your own question. And describe what you mean by "the data received in between when the slot is still getting executed" it is not clear – Benjamin T Oct 04 '17 at 19:01
  • Please refer: [Why a new signal for socket::readyRead() is served even when its earlier slot is still executing?](https://stackoverflow.com/q/46576676/514235). Have typed from mobile, excuse me for any bad formats. – iammilind Oct 05 '17 at 01:53