Search⌘ K

Condition Variables

Explore how condition variables in C++ enable synchronization between threads through notifications. Understand how to use wait and notify methods with unique locks, the role of predicates in wait calls, and the differences between notifying one or all threads. This lesson helps you apply condition variables in typical concurrency scenarios such as producer-consumer workflows while preparing you to handle common issues like lost and spurious wakeups.

We'll cover the following...

Condition variables enable threads to be synchronized via messages. They need the <condition_variable> header, one thread to act as a sender, and the other as the receiver of the message; the receiver waits for the notification from the sender. Typical use cases for condition variables are sender-receiver or producer-consumer workflows.

A condition variable can be the sender but also the receiver of the message.

Method Description
cv.notify_one() Notifies a waiting thread.
cv.notify_all() Notifies all waiting threads.
cv.wait(lock, ...) Waits for the notification while holding a std::unique_lock.
...