0

What is the behavior of a condition variable that is signalled (notify_all) while it is not being currently waited on? Does the next wait return immediately or will the notification be silently dropped?

pmf
  • 7,619
  • 4
  • 47
  • 77
  • Perhaps [this `std::condition_variable` reference](https://en.cppreference.com/w/cpp/thread/condition_variable) can help you? – Some programmer dude Jul 11 '19 at 08:05
  • "This makes it impossible for notify_one() to, for example, be delayed and unblock a thread that started waiting just after the call to notify_one() was made." – pptaszni Jul 11 '19 at 08:06
  • Short answer - notify_all only notifying all threads which currently waiting for the conditional variable. If no thread waiting, no any kernel level synchronization happening only a system call. – Victor Gubin Jul 11 '19 at 08:12
  • 2
    No waiters at the time of a cv notify means effectively nothing. It isn't like an auto-reset-event in Windows. You can't "set" it with state on the chance someone may eventually wait again, and you want that waiter to greedily return immediately. If this is a behavior you're looking for, you're almost assuredly using CV's *wrong*. Do not treat them as state. Rather, consider them a signal mechanism to notify *potential* waiters of change *predicate* data state, which is protected by the mutex you had better be using. It's the predicate data, not the cv, that should convey state. – WhozCraig Jul 11 '19 at 08:25
  • Isn't that something that you can easily test in a short program? – Werner Henze Jul 11 '19 at 08:42
  • @WhozCraig if you make this an answer, I can accept it – pmf Jul 11 '19 at 09:00
  • 1
    A condition variable is used to indicate that a condition has become true. So if it's already true, don't wait. The usual loop on a condition variable handles exactly that case: `while (!condition) cond_var.wait();`. – Pete Becker Jul 11 '19 at 12:55

0 Answers0