Daily bit(e) of C++ | std::condition_variable, std::condition_variable_any
Daily bit(e) of C++ ♻️20, The tools for safely waiting on a shared state: std::condition_variable and std::condition_variable_any.
std::condition_variable and std::condition_variable_any allow multiple threads to wait on a shared state safely.
Condition variables take an acquired lock and a condition and only allow the thread to progress when both the lock is acquired, and the condition is true.
The std::condition_variable only supports std::unique_lock, std::condition_variable_any supports std::stop_token and will work with any lock that provides lock() and unlock() methods.
A thread that wants to modify the shared state needs to acquire the lock, modify the state and then call either notify_one (to wake up one thread waiting on this condition variable) or notify_all (to wake up all threads).