CITS2002 Systems Programming  
prev
next CITS2002 CITS2002 schedule  

Pthreads functions to manage condition variables

Creating and destroying:

Condition variables are declared of type pthread_cond_t, and must be initialized before being used. There are two ways to initialize a condition variable:

  1. Statically, when it is declared. e.g. pthread_cond_t myconvar = PTHREAD_COND_INITIALIZER;
  2. Dynamically, with the pthread_cond_init() function.

thread_cond_destroy() should be used to free a condition variable that is no longer needed.

Waiting and signalling:

pthread_cond_wait() blocks the calling thread until the specified condition is signalled. This function is called while the mutex is locked, and will automatically release the mutex while it waits. After the signal is received and thread is awakened, the mutex is automatically locked for use by the thread. That thread is responsible for unlocking mutex when finished with it.

Using a while loop instead of an if statement to check the waited for condition can help deal with several potential problems, such as:

  • if several threads are waiting for the same wake up signal, they will take turns acquiring the mutex, and any of them can then modify the condition they all waited for,
  • if the thread received the signal in error due to a program bug, and
  • the pthreads library may issue spurious wake ups to a waiting thread (without violating the standard!)

The pthread_cond_signal() function is used to signal (or wake up) another thread waiting on the condition variable. It must be called after the mutex is locked, and must unlock the mutex in order for pthread_cond_wait() function to complete. pthread_cond_broadcast() should be used instead of if more than one thread is in a blocking wait state.

It is a logical error to call pthread_cond_signal() before calling pthread_cond_wait().

Proper locking and unlocking of the associated mutex variable is essential when using these functions. For example:

  • failing to lock the mutex before calling pthread_cond_wait() may cause it NOT to block.
  • failing to unlock the mutex after calling pthread_cond_signal() may not allow a matching pthread_cond_wait() call to complete (it will remain blocked).

 


CITS2002 Systems Programming, Lecture 21, p6, 10th October 2023.