Search code examples
qtqthreadqtconcurrent

Use QWaitCondition in a thread started by QtConcurrent


i have a function that is started by a QTconcurrent run. Inside this function i use QThread (To get the Thread created by the QTConcurrent run) static method to sleep it for some time, but i don't want anymore to use time to activate it, i'd like to use a WaitCondition to wake the thread in another point of the execution, but i searched a lot and don't find any case like this. I only see WaitConditions inside run() methods. Is there some way to use QWaitCondition in a thread started by QtConcurrent?


Solution

  • You also need a mutex:

    void work(QMutex* mutex, QWaitCondtion* cond, volatile bool* wake){
        //do work
        {
            QMutexLocker locker(mutex);
            while(!*wake){
                cond->wait(mutex);
            }
        }
        //do more work
    }
    

    The loop is necessary to avoid spurious wakeups and let the thread fall through if wake is already set to true. Locking over the entire loop is needed to avoid various race conditions.

    You wake the thread with:

    {
        QMutexLocker locker(mutex);
        *wake = true;
        cond->wakeOne();
    }