Synchronisation primitive with std::mutex to block a thread while another thread modifies a shared variable, called condition. The waiting thread sleeps until another thread notifies its condition variable causing it to wake up.
Suppose we have the following variables:
std::mutex mutex;
bool condition;
std::condition_variable cvFor a thread to wait on cv:
- If
condition == true, don’t have to do anything - Acquire a unique lock on the mutex like `std::unique_lock lk{mutex}
- Call
cv.wait(lk)- This will release the lock and wait on the condition variable. The lock will be atomically acquired when the condition variable is notified and the thread wakes up
- Recheck the condition, if not
true, go back to step 2- This recheck is due to spurious wakeup
For a thread to set the condition and notify thread waiting on the condition variable:
- Acquire a lock on
mutex - Set
condition = true - Call
cv.notify_one()orcv.notify_all().- This will notify a thread and wake it up. Observe that the waiting thread won’t return from the
wait()call until this thread releases the lock.
- This will notify a thread and wake it up. Observe that the waiting thread won’t return from the