Condition variables are generally used such that the state they refer to is modified under a mutex. However, when the state is just a single set-only flag, there's no need for a mutex to prevent simultaneous execution. So one might want to do something like this:
flag = 1;
pthread_cond_broadcast(&cvar);
However, this is only safe if pthread_cond_broadcast
implies a write memory barrier; otherwise, the waiting thread may see the condition variable broadcast before the flag write. That is, the waiting thread may awaken, consume the cvar signal, but see the flag still 0
.
So, my question is: Do the pthread_cond_broadcast
and pthread_cond_signal
calls imply a write memory barrier? If so, where is this specified in the relevant POSIX (or other) specifications? The spec seemed unclear on this point.
Note: I am aware that, in practice, this does result in a memory barrier (on Linux, because thread awakening implies a full CPU memory barrier, and the cross-library function call implies a compiler memory barrier). However, I'm interested here in what the spec guarentees.
pthread_cond_broadcast()
is a memory barrier (pubs.opengroup.org/onlinepubs/9699919799/basedefs/…). But as your answer details nicely, that's not useful for the purpose asked about. – Hydrosphere