jeudi 5 novembre 2015

Execute a "wait callback" during the wait for a std::condition_variable to be notified

I'm using a std::condition_variable this way :

void wait()
{
    std::unique_lock<std::mutex> lock(m_stateCompletedMutex);

    m_waitCondition.wait(lock, [this](){return (m_state == STATE_COMPLETED);});
}

I'm pretty happy with this, but now I would like to execute some code "during the wait" (I don't know if I can say it this way, but this is the idea) for example to update the GUI or to increment an wait counter, or anything else.

Saying we're using Qt, I've tried something like this :

void wait()
{
    std::unique_lock<std::mutex> lock(m_stateCompletedMutex);

    while (m_state != STATE_COMPLETED)
    {
        m_waitCondition.wait(lock);

        // Use this an example, it could be any code, executed in the waiting thread
        qApp->processEvents(QEventLoop::ExcludeUserInputEvents);
    }
}

The goal here is to keep the GUI responsive (at least to system events, not user inputs) while we are waiting for a working thread to be completed.

I have two questions about this code :

1/ Is it the good way to do that, or is there a better method to execute code "while waiting"

2/ How often is executed the "waiting code" (the qApp->processEvents call in my example) ? Is it system dependent ? Or does it depends on the current CPU load or anything else ? Or should I use m_waitCondition.wait_for to ensure a minimum frequency call ?

About point 2/, I've tested to monitor it (with std::chrono::high_resolution_clock) and the delay seems to be anything between 200ms and 4000ms in my application, and I think this is a big range.

Aucun commentaire:

Enregistrer un commentaire