Steve M
Steve M

Reputation: 9784

Ignore spurious wakeups, condition_variable::wait_for

Documentation says that the second overload with the Predicate can be used to avoid spurious wakeups. I'm not seeing it, how can I modify my code to ensure that wait_for is not spuriously awakened?

while(count_ > 0) {
    if (condition_.wait_for(lock, std::chrono::milliseconds(timeOut_)) ==
            std::cv_status::timeout)
        break;
}

Upvotes: 2

Views: 1425

Answers (1)

Dietmar Kühl
Dietmar Kühl

Reputation: 153840

The documentation is misleading: there are possibly spurios wake-ups but wait_for() with a predicate will only return when the predicates us true. That is, when using the predicate version it appears as if there are no spurious wake-ups. You can possibly detect if there were spurious wake-ups by recording how often the predicate got executed.

You'd use it like

if (condition_.wait_for(lock,
                        std::chrono::milliseconds(timeOut_),
                        [&](){ return count_ <= 0; }) ==
        std::cv_status::timeout) {
    // deal with timeout here
}

Upvotes: 1

Related Questions