Conditional Variable in Pthread

Conditional variable is used alongside with #mutex to have fine control of the threads’ execution’s sequence. This could improve the synchronisation of all the threads as they could continue their execution only when they have been signalled to do so.

In pthread, before using the conditional variable, initialise it by creating an object of pthread_cond_t and call the function pthread_cond_init on it. Note the similar syntax it shares with #mutex. In order to order (pun intended) the thread to wait in line rather than just continue its execution, we need to call pthread_cond_wait with a mutex that pass into it. After that, to destroy a pthread_cond_t object, call pthread_cond_destroy at the end of the program.

pthread_cond_t cond;

// in the program
pthread_cond_init(&cond, NULL);

// in the threads that should wait
pthread_cond_wait(&cond, &mutex);

// at the end of the program
pthread_cond_destroy(&cond);

Depends on the situation, one would use either pthread_cond_signal or pthread_cond_broadcast to unblock the execution. pthread_cond_signal only unblock one thread at a time. In contrast, pthread_cond_broadcast send the signal to wake up all the waiting threads.

// only unblock one at a time
pthread_cond_signal(&cond);

// unblock all the waiting threads
pthread_cond_broadcast(&cond, &mutex);

Static Initialiser

Just like #mutex, conditional variable could use static initialiser to initialise itself in order to reduce the number of code.

pthread_cond_t cond = PTHREAD_COND_INITIALIZER;

There is no need to call pthread_cond_init and pthread_cond_destroy. However, it is always a good practice to keep pthread_cond_destroy.

#multithreading #pthread