skip to content

In C++, what does std::condition_variable::wait(lock, pred) guarantee when it returns, and why prefer it to a bare wait(lock)?

level: middleimportance: must knowfreq 72%

answer

  1. the standard spells it as a loop
  2. checks before it ever blocks
  3. while (!pred()) wait(lock);
  4. timed overloads return pred()

basics

~20 s

wait(lock, pred) is specified as while (!pred()) wait(lock);, so it returns only with the mutex held and pred() true. It absorbs spurious wake-ups and never blocks when the condition already holds; a bare wait(lock) can return with the condition false.

solid answer

~40 s

The standard defines the predicate overload as `while (!pred()) wait(lock);`. Two things follow. It checks the predicate **before** blocking, so a notification that happened before the call is not needed — the state already says so. And it rechecks after every wake-up, so a spurious return or a wake-up meant for another waiter puts the thread back to sleep. On return the mutex is held and `pred()` was true under it. In a bounded queue between a network reader and a parser, `pop` waits on `not_empty` with `[&]{ return !q.empty(); }` and `push` on `not_full` with a size check. The timed overloads `wait_for` and `wait_until` with a predicate return `bool`: the value of `pred()` at the end, which says whether the condition holds, not merely whether the timeout fired.

code

cpp · 45 lines
cpp
#include <condition_variable>
#include <cstddef>
#include <deque>
#include <iostream>
#include <mutex>
#include <string>
#include <thread>

class BoundedQueue {
public:
    explicit BoundedQueue(std::size_t cap) : cap_(cap) {}
    void push(std::string packet) {
        std::unique_lock<std::mutex> lk(m_);
        not_full_.wait(lk, [&] { return q_.size() < cap_; });
        q_.push_back(std::move(packet));
        lk.unlock();
        not_empty_.notify_one();
    }
    std::string pop() {
        std::unique_lock<std::mutex> lk(m_);
        not_empty_.wait(lk, [&] { return !q_.empty(); });
        std::string p = std::move(q_.front());
        q_.pop_front();
        lk.unlock();
        not_full_.notify_one();
        return p;
    }
private:
    std::mutex m_;
    std::condition_variable not_empty_, not_full_;
    std::deque<std::string> q_;
    std::size_t cap_;
};

int main() {
    BoundedQueue q(2);
    std::thread reader([&] {
        for (int i = 0; i < 5; ++i) q.push("packet " + std::to_string(i));
    });
    std::thread parser([&] {
        for (int i = 0; i < 5; ++i) std::cout << q.pop() << '\n';
    });
    reader.join();
    parser.join();
}

go deeper

for a junior

Remember to write cv.wait(lock, [&]{ return condition; }) rather than a bare wait in an if, and that the lambda reads state guarded by the same mutex.

for a middle

Quote the equivalence while (!pred()) wait(lock); and walk through what it absorbs: spurious returns, notifications that came first, items taken by another consumer.

for a senior

Read the bool from the timed predicate overloads correctly, choose one or two condition variables for a bounded queue, and pick notify_one or notify_all from that.

for a principal

Weigh a hand-written condition-variable queue against a semaphore-based or library queue for the team; most bugs here come from re-implementing the same queue many times.

## The exact equivalence `std::condition_variable` has a template overload `template<class Predicate> void wait(unique_lock<mutex>& lock, Predicate pred)`. The draft standard does not describe it in prose; it gives its **effects** as code: ```cpp while (!pred()) wait(lock); ``` So the predicate is evaluated with the mutex held, first before any blocking and then again after every return from the plain `wait`. When the call returns, the mutex is held and the predicate has just returned `true` under that mutex. Any exception thrown by `pred` propagates out of `wait`. ## What the loop protects against - **Spurious wake-ups.** The standard says the plain `wait` "will unblock when signaled by a call to `notify_one()` or a call to `notify_all()`, or spuriously". A spurious return leaves the state unchanged, so the loop goes back to sleep. - **A notification that came first.** If the producer pushed and notified before the consumer reached `wait`, nobody was blocked, and the notification had no effect: `notify_one` only "unblocks one of those threads" that are blocked at that moment. The predicate overload checks the queue first and does not block at all. - **Stolen wake-ups.** Another consumer may take the item between the notify and this thread relocking the mutex. The loop sees the queue empty again and waits again. - **Wrong-kind wake-ups.** With `notify_all`, every waiter wakes; those whose condition is still false go back to sleep. A bare `wait(lock)` inside an `if` is exposed to all four. ## A bounded queue with two condition variables The worked case is a queue between a **network reader** thread that pushes packets and a **parser** thread that pops them, with a capacity so that a fast reader cannot exhaust memory. It uses one mutex and two condition variables: - `push` waits on `not_full` with `[&]{ return q.size() < cap; }`, appends, then calls `not_empty.notify_one()`. - `pop` waits on `not_empty` with `[&]{ return !q.empty(); }`, removes the front, then calls `not_full.notify_one()`. With two condition variables each notification goes to a thread waiting for exactly that condition, so `notify_one` is enough. With a **single** condition variable shared by both conditions, `notify_one` might wake a producer when a consumer was needed; the woken producer rechecks, sleeps again, and the consumer that should have run stays blocked. One shared condition variable therefore needs `notify_all`. ## The timed overloads with a predicate | Call | Returns | Meaning of the result | |---|---|---| | `wait(lock, pred)` | `void` | returns only when `pred()` is `true` | | `wait_for(lock, rel_time, pred)` | `bool` | the value of `pred()` when it stopped waiting | | `wait_until(lock, abs_time, pred)` | `bool` | the value of `pred()` when it stopped waiting | | `wait_for(lock, rel_time)` | `std::cv_status` | `timeout` or `no_timeout`; says nothing about the state | The standard specifies the predicate `wait_until` as: loop while `!pred()`; if the plain timed wait returns `cv_status::timeout`, `return pred();`; otherwise keep looping, and `return true` once the predicate holds. Its note says the result "indicates whether the predicate evaluated to `true` regardless of whether the timeout was triggered". So `false` means "the deadline passed and the condition is still false", and `true` can arrive exactly at the deadline. Code that treats `true` as "notified" and `false` as "timed out" is right about the condition, which is what it should care about. ## Exceptions and the lock The predicate overload can throw: its specification says it throws "any exception thrown by `pred`". Because the predicate always runs with the mutex held, an exception leaves the `unique_lock` owning the mutex, and the lock's destructor releases it during unwinding, so nothing leaks. The other failure is different: if `wait` cannot relock the mutex on the way out, the postcondition cannot be met and the standard says `std::terminate` is called. That is why `wait` itself is specified as throwing nothing; a failure there ends the program instead of returning without the lock. ## Pitfalls - A predicate that reads state the producer changes **without** the mutex: the check is then a data race, or, with an atomic, a lost wake-up. - A predicate with side effects: it runs an unspecified number of times. - A predicate that is expensive: it runs once per wake-up with the mutex held, delaying every producer. - A `wait_until` deadline taken from `std::chrono::system_clock`: a wall-clock adjustment can move it; `wait_for` with a duration, or a `std::chrono::steady_clock` time point, measures elapsed time.

  • Why does the queue use two condition variables instead of one?
    Producers wait for "not full" and consumers for "not empty". With one condition variable for both, `notify_one` may wake a thread of the wrong kind, which rechecks its predicate and sleeps again while the thread that could make progress stays blocked. Two condition variables let each side `notify_one` exactly the kind of waiter that can now proceed, instead of `notify_all` waking everyone.
  • If wait_for with a predicate returns true, can you conclude that no timeout happened?
    No. The predicate `wait_for` returns `pred()` when it stops, so it can return `true` even when the deadline expired, as long as the condition became true by then. The result answers "does the condition hold?", which is what the caller should branch on; the plain `wait_for` without a predicate is the one that reports `cv_status::timeout`.
  • Does the predicate run with the mutex held?
    Yes. The overload is `while (!pred()) wait(lock);` and `wait` always returns with the mutex locked, so every call to `pred` happens while the caller owns the mutex. That is why the predicate can read the queue directly, and why the producer must change the queue under the same mutex.

  • wait(lock, pred) blocks at least once before checking the predicate
  • Spurious wake-ups are a platform bug that modern C++ libraries have fixed
  • wait_for with a predicate returns false whenever the timeout fired
  • notify_one remembers the signal until some thread waits
  • One condition variable for both full and empty works fine with notify_one