![]() |
CITS2002 Systems Programming |
← prev | next → | ![]() |
![]() |
|||
Pthreads functions to manage condition variablesCreating 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:
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:
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:
CITS2002 Systems Programming, Lecture 21, p6, 10th October 2023.
|