Suppose a condition variable is used in a situation where the signaling thread modifies the state affecting the truth value of the predicate and calls pthread_cond_signal
without holding the mutex associated with the condition variable? Is it true that this type of usage is always subject to race conditions where the signal may be missed?
To me, there seems to always be an obvious race:
- Waiter evaluates the predicate as false, but before it can begin waiting...
- Another thread changes state in a way that makes the predicate true.
- That other thread calls
pthread_cond_signal
, which does nothing because there are no waiters yet. - The waiter thread enters
pthread_cond_wait
, unaware that the predicate is now true, and waits indefinitely.
But does this same kind of race condition always exist if the situation is changed so that either (A) the mutex is held while calling pthread_cond_signal
, just not while changing the state, or (B) so that the mutex is held while changing the state, just not while calling pthread_cond_signal
?
I'm asking from a standpoint of wanting to know if there are any valid uses of the above not-best-practices usages, i.e. whether a correct condition-variable implementation needs to account for such usages in avoiding race conditions itself, or whether it can ignore them because they're already inherently racy.