2 ms·
Not sure why this is flagged, but there's nothing actually special about atomics here, I thought this was fairly common knowledge that when using condition vari
by krackers 3y ago
Not sure why this is flagged, but there's nothing actually special about atomics here, I thought this was fairly common knowledge that when using condition variables you must always couple them with a mutex to provide a critical region and avoid lost wakeup. This is easier to see with the no-abstrations pthread version:
On the waiter side
pthread_cond_lock(&mutex)
while (!predicate) {
pthread_cond_wait(&cvar, &mutex);
}
On the signaler side
pthread_mutex_lock(&mutex);
toggle_predicate(&predicate);
pthread_mutex_unlock(&mutex);
pthread_cond_signal(&cvar);
(Note that it's safe to signal after unlock, although a bit more error-prone as you have to be careful when destroying the cvar). The mutex serves two key purposes: first is providing acq/rel semantics on observations of predicate, the second is that it provides a barrier region to ensure that the predicate is either changed before the waiter enters into the wait loop, or after the waiter has added itself to the wait queue so that signal will wake it up.
Changing the predicate var to atomic allows you to get rid of the first one (and I think it can in fact be a relaxed atomic since mutex lock already has acq/rel semantics), but you still need it to serve the second purpose.
See this SO answer for more info: https://stackoverflow.com/a/9918764 https://stackoverflow.com/a/9918764