Home > Back-end >  Is the content of a predicate in c wait_for method mutex protected or not?
Is the content of a predicate in c wait_for method mutex protected or not?

Time:11-26

Suppose, countMe is a global variable and I am launching 10 threads at the same time to this while loop, is the variable countMe mutex protected in the predicate? I think because when the code reaches to the wait_for it unlocks and releases the lock, the variable countMe isn't mutex protected. Am I right?

while (true)
{
    std::unique_lock<std::mutex> lock(mtx_kill);
    cv_kill.wait_for(lock, 500ms, [&]() {  countMe; return killFlag; });

    if (killFlag)
    {
        break;
    }
}

CodePudding user response:

Am I right?

Nope, you're wrong.

I think because when the code reaches to the wait_for it unlocks the lock, the variable countMe isn't mutext protected.

No, the mutex is in a locked state when the lambda gets evaluated. Guaranteed.

cppreference.com describes the predicate version of wait_for in terms of wait_until, which is described as follows:

while (!stop_waiting()) {
    if (wait_until(lock, timeout_time) == std::cv_status::timeout) {
        return stop_waiting();
    }
}

Note that the initial state of the mutex is that it's locked. The predicate, called "stop_waiting" here, is always called when the mutex is in the locked state.

You can think of wait_for as just a predicate-less wait, with the additional predicate check as a discrete, separate step. After wait returns the mutex gets relocked, and that happens before the predicate, your lambda, executes. If it votes thumbs down the mutex gets, once again, atomically unlocked together with the condition variable getting waited on again.

P.S. The above discussion presumes that your countMe is always accessed, elsewhere, with the same lock being held. This is presumed by your question, but merely formally noted.

  • Related