-
Notifications
You must be signed in to change notification settings - Fork 37
CountDownLatch and Spurious Wakeups
Details Rudro discovered after reviewing and merging : 1880d77
The reason for having a loop is due to "spurious wakeup"s. While it appeared to be almost a bug in the NSCondition API, it seems that this, while somewhat counterintuitive, is by design.
We don't have the source to NSCondition, but it seems that it's probably just a slim wrapper around pthread_cond_wait and pthread_cond_timedwait This issue exists at the pthread layer, so it's not really NSConditions fault Spurious wakeups are mentioned clearly in the man pages : http://pubs.opengroup.org/onlinepubs/7908799/xsh/pthread_cond_wait.html While it seems to be a strange API choice, it seems that someone balanced performance with was-of-use of the API and consciously chose better performance over a simpler API. Wiki page about it : https://en.wikipedia.org/wiki/Spurious_wakeup Quote from that page (and elsewhere) :
This means that when you wait on a condition variable, the wait may (occasionally) return when no thread specifically broadcast or signaled that condition variable. Spurious wakeups may sound strange, but on some multiprocessor systems, making condition wakeup completely predictable might substantially slow all condition variable operations. The race conditions that cause spurious wakeups should be considered rare.