简体   繁体   中英

Does condition_variable::wait_for return true when cv is notified

here is a small code snippet

request_ptr pop()
{
    request_ptr rp;

    std::unique_lock<std::mutex> lock(cv_mtx);
    auto time = std::chrono::milliseconds(10000);
    if (!cv.wait_for(lock, time, [this] { return !this->is_empty(); }))
    {
        return rp;
    }

    std::lock_guard<std::mutex> mtx_guard(mtx);
    rp.reset(new request(std::move(requests.front())));
    requests.pop();
    return rp;
}

How does wait_for behave when cv is notified? Does it return true without check of returned value of is_empty ? Or it returns true only if is_empty returns true ?

According to [thread.condition.condvar]/36 the call...

cv.wait_for(lock, rel_time, pred);

is equivalent to...

cv.wait_until(lock, chrono::steady_clock::now() + rel_time, std::move(pred));

which is, in turn , equivalent to...

while (!pred())
    if (wait_until(lock, abs_time) == cv_status::timeout)
        return pred();
return true;

So the value returned by wait_for should be the current value as returned by the predicate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM