Home > Software design >  In QT,how to make two signals trigger the slot function synchronously in the main thread?
In QT,how to make two signals trigger the slot function synchronously in the main thread?

Time:07-21

I am new to QT programming.In my project,i have created 2 Qthreads.And they will emit signnals seperately to the main thread.Because of the difference in how much data is processed in the two child threads, I cannot guarantee that the main thread will receive the signal at the same time.So is there any way to make the two signals recieved by the main thread at the same time?The QT version i am using is 5.12.1.The connnet function i have written is as below.Thanks in advance for your reply!

connect(m_oripoint,SIGNAL(one_time_rec(double)),this,SLOT(showpic(double)),Qt::BlockingQueuedConnection);
connect(m_postpoint,SIGNAL(two_time_rec(double)),this,SLOT(showpic_2(double)),Qt::BlockingQueuedConnection);

m_oripoint and m_postpoint are objects that I process in two threads, and they will send showpic and showpic_2 signals to the main thread later.

CodePudding user response:

As you have only one main thread, it can only process signals one after the other. There is no way they can be processed at the same time. So you usually do not care for signals to be received at the same time. Signals come (or not) and whenever they come, they are processed - that is the idea of event-driven programming.

Sidenote: I have never seen a real use case for Qt::BlockingQueuedConnection - are you sure that this is what you need? Usually, Qt::QueuedConnection is good enough for processing events from a secondary thread in the main (GUI) thread.

CodePudding user response:

As clarified by @Jens answer, two signals cannot be processed at the same time.

Your requirement is to intimate the main thread at once, when both the child threads have finished their respective data processing.

Here's one way to achieve it:

  • Create a new signal: newSig.
  • Create two new slots: newSlot1 & newSlot2.
  • Connect the signals from the child threads to newSlot1.
  • Connect newSig to newSlot2.
  • In newSlot2, trigger showpic() & showpic_2().
  • In newSlot1, collect the values from the child threads signals.
    When both values are received, emit newSig.

This way, you wait to emit the newSig until both threads have finished their respective data processing. Therefore you guarantee that your showpic() & showpic_2() are triggered only after both threads have finished their respective data processing.

  • Related