- Condition variables are one of the synchronization mechanism which enables the thread to wait until particular condition holds.
- For example, parent thread blocks itself until the child thread completes execution. In this case, parents go for a spinning that keeps looping until the child finishes. This results in CPU cycle wastage.
- Thus condition variable helps the parent to sleep rather than spinning until the condition that is child finishes becomes true.
- When a thread goes to sleep, it releases the lock and re-acquires the lock once the condition becomes true and execute.
Condition Variables API:
- Declaring a condition variable:
pthread_cond_t cond_var = PTHREAD_COND_INITIALIZER; - A condition variable has two operation associated with it: wait() and signal()
- Waiting API:
pthread_cond_wait ( pthread_cond_t *cond_var, pthread_mutex_t lock);
The responsibility of wait() is to release the lock and put the calling thread to sleep. - Signalling API:
pthread_cond_signal(pthread_cond_t *cond_var);
When the condition becomes true, signal is made to the sleeping thread and is woken up and lock is re-acquired before returning to the caller.
- Waiting API:
- Note:
- wait() API takes mutex as one of the parameter, since even the condition variable may face race condition and hence needs synchronization.
- Always hold the lock when calling signal() or wait().
- Always have while loop to test the condition.
- Example of Parent thread and child Thread
#include <stdio.h> #include <pthread.h> #include <string.h> #include <stdlib.h> pthread_cond_t c = PTHREAD_COND_INITIALIZER; pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; int done =0; void thr_exit() { pthread_mutex_lock(&lock); done =1; /* It signals parents, and parent is woken up */ pthread_cond_signal (&c); pthread_mutex_unlock (&lock); } void *child(void *arg) { printf("\n Child executing\n"); thr_exit(); } void thr_join() { pthread_mutex_lock (&lock); /* Parent is sleeping for value for done to be non zero */ while (done ==0) pthread_cond_wait(&c, &lock); pthread_mutex_unlock(&lock); } int main() { pthread_t th_id; int res = pthread_create (&th_id, NULL, child, NULL); if (res) { printf("\n Creating thread child fails %s\n", strerror(res)); exit(0); } /* Write equivalent function to pthread_join which puts the parent spinning * Here we want parent to sleep rather than spinning by use condition variable */ thr_join(); printf("\n Parent exit successful\n"); return 0; }
Output:
[aprakash@wtl-lview-6 thread]$ gcc condition_var.c -lpthread [aprakash@wtl-lview-6 thread]$ ./a.out Child executing Parent exit successful
Diag-1: Condition variables

Relevant Posts:
- Thread Synchronization
- Critical Section
- Race Condition
- Semaphore
- Mutual Exclusion(Mutex)
- Mutex Vs Semaphore
- Spinlock
- Spinlock Vs Mutex
spinlock ›
Categories: Operating system (OS)
Leave a Reply