alexander.sivak
alexander.sivak

Reputation: 4730

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?

Upvotes: 1

Views: 530

Answers (1)

G.M.
G.M.

Reputation: 12899

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.

Upvotes: 1

Related Questions