...
Condition variables must be used inside a while
loop. (see See CON36-C. Wrap functions that can spuriously wake up in a loop for more information.) . To guarantee liveness, programs must test the while
loop condition before invoking the cnd_wait()
function. This early test checks whether another thread has already satisfied the condition predicate and has sent a notification. Invoking the cnd_wait()
function after the notification has been sent results in indefinite blocking.
...
In this example, all threads share a condition variable. Each thread has its own distinct condition predicate because each thread requires current_step
to have a different value before proceeding. When the condition variable is signaled, any of the waiting threads can wake up.
The following table illustrates a possible scenario in which the liveness property is violated. If, by chance, the notified thread is not the thread with the next step value, that thread will wait again. No additional notifications can occur, and eventually the pool of available threads will be exhausted.
...
Another compliant solution is to use a unique condition variable for each thread (all associated with the same mutex). In this case, cnd_signal()
wakes up only the thread that is waiting on it. This solution is more efficient than using cnd_broadcast()
because only the desired thread is awakened.
Note that the The condition predicate of the signaled thread must be true; otherwise, a deadlock will occur.
...