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:

  1. Wait: A thread waiting on a condition variable suspends execution and releases the lock.
  2. Signal: Another thread signals the condition variable to wake up one (or all) waiting threads.
  3. Lock Association: Condition variables are always associated with a mutex or lock to ensure atomicity.

How Do Condition Variables Work?

Steps:

  1. A thread acquires a lock (mutex) and checks a condition.
  2. If the condition is false, the thread waits on the condition variable. This releases the lock and suspends the thread.
  3. Another thread, upon modifying shared data, signals the condition variable.
  4. 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.