In the producer and consumer model, we usually use pthread_cond_wait
to put the thread into sleep while the execution is not statifised. For example,
1 | // When the product queue is full, put the producer into wait condition |
Instead of forwarding to the production code, thread goes back to the condition check in the while
.
Why? Follwing is an example,
1 | Thread 1 Thread 2 Thread 3 |
When thread 2
sends out the condition signal, there may be another thread, e.g., thread 3
may steal
the conditional flag and disquailify the wake up condition. There is because the thread must release the mutex before waiting. Unless it is guaranteed that only one thread can wait on that condition, e.g., one producer
and one consumer
.