Condition Variables
This lesson explains condition variable such as wait s and their usage in C++ for multithreading purposes.
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 . |
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 point for the notification while holding a std::unique_lock . |
The subtle difference between cv.notify_one
and cv.notify_all
is that cv.notify_all
will notify all waiting threads. In contrast, cv.notify_one
will notify only one of the waiting threads while the other threads remain in the wait state. Before we cover the gory details of condition variables - which are the three dots in the wait operations - here is an example.
Get hands-on with 1400+ tech skills courses.