Condition Variables - aryanjoshi0823/5143-Operating-System GitHub Wiki
A condition variable is a data structure used to manage threads' execution based on specific conditions.
- Threads can wait on a condition variable, effectively suspending execution until a particular condition is met.
- Another thread signals the condition variable to wake up waiting threads when the condition becomes true.
Key Concepts:
- Wait: A thread waiting on a condition variable suspends execution and releases the lock.
- Signal: Another thread signals the condition variable to wake up one (or all) waiting threads.
- Lock Association: Condition variables are always associated with a mutex or lock to ensure atomicity.
How Do Condition Variables Work?
Steps:
- A thread acquires a lock (mutex) and checks a condition.
- If the condition is false, the thread waits on the condition variable. This releases the lock and suspends the thread.
- Another thread, upon modifying shared data, signals the condition variable.
- The waiting thread is awakened, re-acquires the lock, and rechecks the condition.
Use Cases:
- Producer-Consumer Problem
- Thread Synchronization
- Resource Management
Condition Variables vs. Semaphores
Aspect | Condition Variables | Semaphores |
---|---|---|
Purpose | Thread communication based on conditions. | Managing resource access or mutual exclusion. |
Dependency | Requires a lock (mutex) for synchronization. | Works independently or with a lock. |
State Persistence | No state persistence; conditions must be rechecked. | Maintains a count; tracks resource availability. |
Signaling | Explicit signal/broadcast needed to wake threads. | Automatically unblocks threads when incremented. |
Spurious Wakeups | Can occur; conditions must be rechecked in a loop. | Does not have spurious wakeups. |
Use Case | - Producer-Consumer problem. | - Thread pool management or limiting resources. |