What is the difference between a condition variable and busy-waiting? How does std::condition_variable work?
Last updated
Busy-waiting spins in a loop (e.g. while(!ready){}) checking a condition, burning a CPU core. It is only worth it for extremely short waits.
A
std::condition_variableputs the thread to sleep (zero CPU) until another thread callsnotify_one()ornotify_all()after changing shared state.It pairs with a
std::mutex:wait()atomically releases the lock, sleeps, and reacquires on wakeup. Always check a predicate in a loop (or use the predicate overload) to handle spurious wakeups.