In parallel computing, a condition variable is used to block a thread until a condition is true (after which it continues execution). It’s defined as an explicit queue that threads can put themselves on when some condition isn’t as desired (i.e., it queues the thread and waits for the condition). Then, when some other thread changes the condition, it can wake one or more of those waiting threads by signalling on the condition and allow them to continue.

Language-specific

In C

Condition variables are provided on POSIX systems within the pthread library as the pthread_cond_t type. The API is given below:

Condition variables

  • pthread_cond_init: initialises the condition variable. Must be called.
  • pthread_cond_destroy
  • pthread_cond_signal: wakes up the first thread in the queue.
  • pthread_cond_broadcast: wakes up all threads in the queue.
  • pthread_cond_wait(pthread_cond_t *c, pthread_mutex_t *m): adds a thread to the queue. Takes two input variables: a condition variable and a mutex (so enqueueing operations are atomic).
    • It doesn’t contain data races — it adds itself to the queue for the condition variable, unlocks the mutex, then gets blocked (it can no longer be scheduled to run).
    • The thread calling wait needs another thread to call signal or broadcast. If it’s selected, it gets unblocked, tries to lock the mutex again, and wait returns when it gets it.
  • pthread_cond_timedwait
Link to original
As usual with pthread types, we have to initialise them before use. Then, we have two basic operations: wait() and signal().