In C++, why does std::condition_variable::wait take a std::unique_lock<std::mutex> and refuse a std::lock_guard?
answer
- the mutex is released while sleeping
- unlock, block, relock
- lock_guard has no unlock()
- condition_variable_any takes any lockable
basics
~10 sstd::condition_variable::wait must release the mutex while the thread sleeps and lock it again before returning, so it takes a std::unique_lockstd::mutex, which can unlock and relock. std::lock_guard cannot, so the call does not compile.
solid answer
~40 s`wait` atomically calls `lock.unlock()` and blocks, and when it is woken it calls `lock.lock()` before returning, so the caller holds the mutex again on return. That needs a lock object that can give its mutex up and take it back: `std::unique_lock<std::mutex>` has `unlock()` and `lock()`; `std::lock_guard` has neither, and every `std::condition_variable::wait` overload takes `unique_lock<mutex>&`, so `cv.wait(guard, pred)` is a compile error. The mutex must be the one that protects the data the predicate reads, and every thread waiting on the same condition variable at the same time must use the same mutex. If you need another lock type, `std::condition_variable_any` accepts anything with `lock()` and `unlock()`.
code
cpp · 13 lines#include <condition_variable>
#include <mutex>
std::mutex m;
std::condition_variable cv;
bool ready = false;
void consumer() {
std::lock_guard<std::mutex> lk(m);
cv.wait(lk, [] { return ready; }); // does not compile
}
int main() {}go deeper
Recall the shape: a std::mutex, a std::unique_lock around it, and cv.wait(lock, predicate). Know that lock_guard cannot be used for the waiting side and why.
Explain the three steps of wait: atomic unlock-and-block, relock on wake, return with the lock held, and why only unique_lock can take part in that.
Point out what compiling does not prove: the same mutex for every waiter, the predicate recheck, and the producer changing state under that mutex.
Know when condition_variable_any earns its cost (shared or custom locks, stop tokens) and when a latch or semaphore removes the need for a hand-written condition variable altogether.
## What `wait` does with the lock A **condition variable** lets a thread sleep until another thread changes some shared state and tells it so. In C++ the type is `std::condition_variable` from `<condition_variable>`, and the state it guards is always protected by a `std::mutex`. The draft standard specifies `void wait(unique_lock<mutex>& lock)` in three steps: 1. **Atomically** call `lock.unlock()` and block on the condition variable. 2. When unblocked — by `notify_one()`, by `notify_all()`, or **spuriously** — call `lock.lock()`, possibly blocking on the mutex. 3. Return. The postcondition is that `lock.owns_lock()` is `true` and the calling thread holds the mutex. The atomic unlock-and-block is the whole point. If the thread unlocked first and then went to sleep as two separate steps, a notifier could slip between them and the wake-up would be lost. The library does both as one step with respect to that mutex, and that is why it must be handed the lock object rather than taking the mutex itself. ## Why `std::lock_guard` cannot be passed `std::lock_guard<M>` is the simplest RAII lock: its constructor locks, its destructor unlocks, and it has no other member functions. It cannot release the mutex in the middle of its lifetime, so it cannot hand the mutex over for the duration of a wait. `std::unique_lock<M>` is the movable, flexible lock: it has `lock()`, `unlock()`, `try_lock()`, `owns_lock()` and `release()`, and it can be constructed deferred or adopting. Every `wait`, `wait_for` and `wait_until` overload of `std::condition_variable` takes a `unique_lock<mutex>&`, so a `lock_guard` matches none of them. Clang with libc++ reports `no matching member function for call to 'wait'`, with the note `no known conversion from 'std::lock_guard<std::mutex>' to 'unique_lock<mutex> &'`. The producer side has no such requirement. A thread that only changes the state and notifies can use a `std::lock_guard` or `std::scoped_lock` around the change, because it never waits. ## What the lock type does not settle Choosing `unique_lock` makes the code compile; it does not make the wait correct. - **The predicate still has to be rechecked.** `wait` may return without a notification, so the waiting code either loops or uses the predicate overload `wait(lock, pred)`. - **The same mutex everywhere.** The standard's precondition says that every thread waiting on one `condition_variable` at the same time passes a lock on the same mutex. Waiting with two different mutexes on one condition variable at once violates that precondition, which is undefined behaviour. - **The lock must be held on entry.** Calling `wait` with an unlocked `unique_lock` violates the precondition `lock.owns_lock()`. - **The lock is held again on return**, even after a spurious wake-up or a timeout, so the code after `wait` can read the shared state directly. ## `std::condition_variable` versus `std::condition_variable_any` | | `std::condition_variable` | `std::condition_variable_any` | |---|---|---| | Lock it accepts | `std::unique_lock<std::mutex>` only | any **BasicLockable** type (`lock()` and `unlock()`) | | Works with `std::shared_lock`, `std::recursive_mutex`, a custom lock | no | yes | | `std::stop_token` wait overloads (C++20) | no | yes | | Cost | can map directly onto the platform's condition variable | may carry extra internal state | The restriction on `std::condition_variable` lets it sit directly on top of the operating system's primitive, which waits on exactly one mutex type. `std::condition_variable_any` is the general version for when the lock is something else. ## A minimal correct pair The waiting side and the notifying side use different lock types for a reason: ```cpp // waiter std::unique_lock<std::mutex> lk(m); cv.wait(lk, [&] { return ready; }); // ... read the shared state; lk is held here // notifier { std::lock_guard<std::mutex> g(m); ready = true; } cv.notify_one(); ``` The waiter needs `unique_lock` because `wait` will release and retake the mutex. The notifier needs only a scope-bound lock around the change, because it never hands the mutex to anyone; a `std::scoped_lock` would do as well. The flag is a plain `bool`, since every access to it happens under `m`. ## Mistakes interviewers listen for - Passing a `std::lock_guard`, then "fixing" the compile error by calling `m.unlock()` by hand before `wait`, which reopens the lost-wake-up window. - Creating the `unique_lock` with `std::defer_lock` and never locking it before `wait`. - Holding a different mutex from the one the producer uses to change the state. - Believing `wait` returns with the mutex unlocked and calling `lock.lock()` again, which throws `std::system_error` with `resource_deadlock_would_occur` because the `unique_lock` already owns the mutex.
- Can the producer that changes the state and calls notify_one use a std::lock_guard?Yes. Only the waiting side needs a lock it can release and retake, because only `wait` hands the mutex back while sleeping. The producer locks with `std::lock_guard` or `std::scoped_lock`, changes the state, and notifies either inside that scope or just after it ends. What it must not do is change the state without taking the same mutex.
- Why does std::condition_variable accept only std::unique_lock<std::mutex> instead of any lock type?Fixing the mutex type lets the implementation wait directly on the platform's own condition variable with that mutex, with no extra bookkeeping. `std::condition_variable_any` lifts the restriction and accepts any type with `lock()` and `unlock()`, such as a `std::shared_lock` or a lock over `std::recursive_mutex`, at the price of more internal machinery.
- std::lock_guard works with wait if you unlock the mutex by hand first
- wait returns with the mutex unlocked, so you must lock it again
- wait keeps the mutex locked while the thread sleeps
- Each waiting thread may use its own mutex on the same condition variable
- Switching to std::unique_lock alone makes a single wait call correct