Condition Variables

Let's talk about condition variables that enable threads to wait until a particular condition occurs.

Condition variables enable threads to be synchronized via messages. They need the header <condition_- variable>. One thread acts as a sender, and the other as a receiver of the message. The receiver waits for the notification of the sender. Typical use cases for condition variables are 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.
cv.wait_for(lock, relTime, ...) Waits for a time duration for the notification while holding a std::unique_lock.
cv.wait_until(lock, absTime, ...) Waits until a time for the notification while holding a std::unique_lock.

The sender and receiver need a lock. In the case of the sender, a std::lock_guard is sufficient because it only once calls lock and unlock. In the case of the receiver, a std::unique_lock is necessary because it typically often locks and unlocks its mutex.

Get hands-on with 1400+ tech skills courses.