Condition variables are a ๐ฅ Synchronization method that allows a thread to wait until itโs notified to resume. Used in conjunction with a ๐ Lock, the condition variable can put a thread to sleep and wait until some condition is fulfilled.
Specifically, the locking flow is as follows:
- Thread acquires a lock, enters a critical section.
- Some condition is unfulfilled. Thread uses the condition variable to wait, and it also gives up the lock in the meantime.
- Sometime later, condition is fulfilled and thread receives a signal broadcast. Thread wakes up and tries to re-acquire the lock. If itโs unsuccessful, it blocks as normal.
- After re-acquiring the lock, thread finishes the rest of the critical section and unlocks.
This is commonly used to avoid busy waits, such as in the Producer-Consumer problem.