0

Thanks in advance.

We are calling some third party API's from our Qt application. As a precautionary measure we are calling them from QtConcurrentRun thread and making main thread wait for a definite timeout using QWaitCondition wait(). The same locked muted that is passed to QWaitCondition wait() is used for locking inside the worker thread function. However, the wait finishes only after the worker thread has finished and signaled using wakeAll(). Consequently, if the worker thread hangs, our main thread also hangs, which defeats our purpose. Is there an alternate way to achieve this?

MyClass:startBackgroundWork()
{
    QMutexLocker lock(m_myMutex);
    bool waitStatus = false;
    QFuture myBackgroundTask = QtConcurrentRun::run(&MyClas::threadProc, &m_waitCondition);
    if(myBackgroundTask.isStared())
    {
        waitStatus = m_waitCondition.wait(&m_myMutex, 200);
    }
    if(waitStatus)
    {
        /// Success
    }
    else
    {
        /// Timeout
    }
}

bool MyClass::threadProc(QWaitCondition* pwaitCondition)
{
    QMutexLocker locker(m_myMutex);
    /// Do stuff here
    pwaitCondition->wakeAll();
}



  • 1
    You may want to use `QFutureWatcher`. – hyde Nov 30 '21 at 10:49
  • 1
    [This](https://stackoverflow.com/a/19903975) might help – Mike van Dyke Nov 30 '21 at 11:10
  • Thank you for your reply.In the above link, the solution with the EventLoop, FutureWatcher seems more viable to me rather than the one with QThread. Anyway, in the sample code provided by me, is it compulsory to use the same mutex inside worker thread proc if there are no shared variables between main thread and worker thread other than the QWaitCondition object? – Rohini Sreekanth Nov 30 '21 at 12:09
  • A wait condition requires a mutex. However, wait condition is a very low level synchronization mechanism, you shouldn't use it in a Qt app, at least not from the main thread. – hyde Nov 30 '21 at 13:11
  • The advantage with QWaitCondition was that it will ensure that the worker starts only after main thread started waiting(thanks to the mutex) and returns whenever it has finished its task or timeout expired. However, with the other 2 solutions, there is no option to ensure that worker starts only after main thread started waiting. Ultimately, main thread will be forced to wait for the timeout, even if worker has finished execution. Please correct me if I am wrong. – Rohini Sreekanth Dec 01 '21 at 03:26
  • 1
    A general note: in Qt, if your main thread is waiting (sleeping), you are doing something a bit wrong. It may be harmless, but more likely it will cause issues, if not now then later. Just don't do it. Use events (signals and slots). – hyde Dec 15 '21 at 09:53

0 Answers0