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 cv

For a thread to wait on cv:

  1. If condition == true, don’t have to do anything
  2. Acquire a unique lock on the mutex like `std::unique_lock lk{mutex}
  3. 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
  4. Recheck the condition, if not true, go back to step 2

For a thread to set the condition and notify thread waiting on the condition variable:

  1. Acquire a lock on mutex
  2. Set condition = true
  3. Call cv.notify_one() or cv.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.

Member Functions