Yes, you do need to lock the mutex somewhere in the signalling / buffer-setting side.
A condition variable must always be paired with some condition over shared state that the waiting thread is waiting for - that's why it's called a condition variable. The waiting side must always re-check the condition it is waiting for after pthread_cond_wait()
returns - it is allowed to return early even if it hasn't been signalled yet. In almost all cases, this means that you should be calling pthread_cond_wait()
in a loop that checks the condition:
pthread_mutex_lock(&mut);
while (!buffer_is_set())
pthread_cond_wait(&cond, &mut);
consume_buffer();
pthread_mutex_unlock(&mut);
The buffer_is_set()
condition is necessarily going to look at some shared state that the other thread is updating, so the other thread must also lock the mutex to prevent racing access to that state:
pthread_lock(&mut);
setting_buffer(); /* Now buffer_is_set() will return true */
pthread_cond_signal(&cond);
pthread_unlock(&mut);
Note that the mutex only needs to be locked around the setting_buffer()
call - it's safe to call pthread_cond_signal()
after unlocking the mutex.