Ben Hutchings wrote:
after which thread B will pick up the lock and write the data and resets the boolean flag. After releasing the lock, threads A will immediately try to re-acquire the lock. <snip>
You might find that this works on your development machine, but it will likely fail elsewhere. There is no guarantee that releasing a mutex that's blocking another thread is will wake that other thread.
This is an interesting question. The situation is that thread B waits on a mutex and thread A first released mutex and then locks it again. POSIX says that: If there are threads blocked on the mutex object referenced by mutex when pthread_mutex_unlock() is called, resulting in the mutex becoming available, the scheduling policy is used to determine which thread shall acquire the mutex. Which I interpret as saying that if B waits on the lock when A releases it, B will acquire the lock, as it's the only thread waiting on the lock. Am I wrong? OTOH hand, I don't understand why flag is needed. Obviously, there are some performance concerns which are not made clear in the original post. - Volodya