0

(Working with Qt 5.15.2) I have a method which receives a signal (sig_responseReady) from the same thread. The purpose of this method is to wait until a response is received. While this method is waiting for the signal, the method is called again because of an event which calls this method (so eventloops get nested). However, the first waitForResponse on the stack does not get the sig_responseReady signal for up to 10 seconds (for no reason I can see), while later called waitForResponse get their signal first.

The result of this design is that I have nested eventloops, which according to this stackoverflow post causes slot/signal handling errors, and should be avoided. I suspect this is the cause of my problem.

Is there a design which accomplishes the same, with only a single eventloop? (I can't come up with it) The function which calls waitForResponse must pause until waitForResponse returns. ..I can't make it asynchronous. I tried replacing eventloop.exec with QCoreApplication::processEvents(QEventLoop::AllEvents,100) in the function below, but still get same strange result. (So maybe nested event loops is not the problem...but I can't figure out the cause)

MyClass::SRequest MyClass::waitForResponse(const QUuid queryID) {

    reentryCount++;  // Static var to determing nesting/depth count
    QEventLoop eventloop;
    qDebug() << "MyClass::waitForResponse connect for uid " << queryID << ", depth " << reentryCount;
    connect(this,&MyClass::sig_responseReady,&eventloop, &QEventLoop::quit); //, Qt::QueuedConnection);  // Allow matching response to stop eventloop
    do {
        eventloop.exec();
        qDebug() << "MyClass::waitForResponse got signal for uid " << queryID;
    } while (!queryResponseReady(queryID) && !queryExpired(queryID));
    qDebug() << "MyClass::waitForResponse exitted loop for signal for uid " << queryID << ", depth " << reentryCount;

    reentryCount--;
    return queryTakeResult(queryID);
}
TSG
  • 4,242
  • 9
  • 61
  • 121
  • It's hard to understand what do you want to achieve, if you connect signal/slot in the same thread it will always be a direct connection, emitting signal will immediately call all connected slots in the order of connection and then return back. If you want to emit a signal with a payload that you want to get processed, you can, for example, emit a signal with a pointer to that payload on the heap. Connect as UniqueConnection and after emitting the receiver processes your payload which is immediately available in the emitter. – Octopussy Feb 03 '22 at 07:17
  • 1
    From the description I have absolutely no idea that you are trying to do and why. Is this supposed to run in the main thread or a secondary thread? Nesting event loop is definitely a bad idea no matter what... However this seems like some kind of XY problem. Please try to rework the problem description. – HiFile.app - best file manager Feb 03 '22 at 08:34

0 Answers0