If you do not block the mutex in a code that changes state and signals, you may lose awakenings. Consider this pair of processes:
Process A:
pthread_mutex_lock(&mutex); while (condition == FALSE) pthread_cond_wait(&cond, &mutex); pthread_mutex_unlock(&mutex);
Process B (invalid):
condition = TRUE; pthread_cond_signal(&cond);
Then consider this possible alternation of instructions, where condition begins as FALSE :
Process A Process B pthread_mutex_lock(&mutex); while (condition == FALSE) condition = TRUE; pthread_cond_signal(&cond); pthread_cond_wait(&cond, &mutex);
condition now TRUE , but process A is stuck waiting for a condition variable - it missed the wake-up signal. If we change process B to lock the mutex:
Process B (correct):
pthread_mutex_lock(&mutex); condition = TRUE; pthread_cond_signal(&cond); pthread_mutex_unlock(&mutex);
... then the above cannot happen; awakening will never be missed.
(Note that you can actually move pthread_cond_signal() immediately after pthread_mutex_unlock() , but this can lead to less optimal scheduling of threads, and you must block the mutex already in this code path due to a change in the condition itself).
caf Dec 31 2018-10-12-31 03:38
source share