Why use pthread_cond_wait in a loop

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
2
3
4
5
6
7
8
// When the product queue is full, put the producer into wait condition
while(q.size() == LIMIT_SIZE) {
pthread_cond_wait(&notfull, &lock);
// When the not empty signal is receiver, wake up the thread.
}
// Production code begin
// xxxx
// Production code end

Instead of forwarding to the production code, thread goes back to the condition check in the while.

Why? Follwing is an example,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
Thread 1                      Thread 2                Thread 3
q.size() == LIMIT (True)
pthread_cond_wait:
1. unlock mutex
2. wait
lock mutex
set condition: not full
pthread_cond_signal
unlock mutex
lock mutex
check condition: not full
1. Doing staff
2. unset condition
unlock mutex
pthread_cond_wait:
1. wake up
2. lock mutex
<thread is awake, but condition is unset>

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.