Talk:cpp/thread/condition variable/wait
From cppreference.com
< Talk:cpp | thread | condition variable
Below is an interesting link to a posting about a possible race condition on (2) where the time between the predicate check and wait is subject to missing a notification.
https://www.modernescpp.com/index.php/c-core-guidelines-be-aware-of-the-traps-of-condition-variables
The proposed solution to put the variable checked in the predicate under the locked mutex when updating it should work regarding the correct update on the next notification. Depending on the code, this may become a bit tedious and an alternative may be to put the notify request under the mutex. It may be useful to add some hint on this pitfall and how to solve it. mikey, 2001:16B8:3F8A:600:7C9A:B26:59BA:A07D 11:49, 19 September 2020 (PDT)
- we already say, in cpp/thread/condition_variable, that the variable checked in the predicate must be modified under the same mutex. Rainer says exact same thing in your link: "Even if you make dataReady an atomic, it must be modified under the mutex" --Cubbi (talk) 12:59, 19 September 2020 (PDT)
- I think this is just one solution to the problem. If the condition variable is atomic you may still modify it without the mutex, but then have to either take the mutex once afterwards or during notify. This may be simpler if there are some conditional branches where you set the conditional variable and want the notification to occur at one place. Or if the condition variable is anyway atomic due to concurrency outside of condition variable scope. It's also good to understand that once you released the lock, a spurious wakeup may make the waiting thread continue and notify is not necessarily the triggering point in the execution flow. If a spurious wakeup shall be avoided to affect the period of modification and notification then best option is to do both change of condition and notify under the mutex. The linux pthread_cond_signal has a paragraph touching the notification under the mutex:
- The pthread_cond_broadcast() or pthread_cond_signal() functions may be called by a thread whether or not it currently owns the mutex that threads calling pthread_cond_wait() or pthread_cond_timedwait() have associated with the condition variable during their waits; however, if predictable scheduling behavior is required, then that mutex shall be locked by the thread calling pthread_cond_broadcast() or pthread_cond_signal().
- Anyway, this is probably too much detail to be put on the pages, so not expecting any updates. mikey, 2001:16B8:3FD7:CD00:157A:E763:4BC4:FA48 10:19, 20 September 2020 (PDT)