Why do you need a while loop while waiting for a condition variable

那年仲夏 提交于 2019-11-28 17:59:01

It is recommended that all threads check the condition after returning from pthread_cond_wait because there are several reasons the condition might not be true. One of these reasons is a spurious wakeup; that is, a thread might get woken up even though no thread signalled the condition.

Source : Spurious wakeup

Spurious wakeups are one reason, but legitimate but extraneous wakeups are another.

Consider:

  1. You put a job on a queue.

  2. You signal the condition variable, waking thread A.

  3. You put a job on a queue.

  4. You signal the condition variable, waking thread B.

  5. Thread A gets scheduled, does the first job.

  6. Thread A finds the queue non-empty and does the second job.

  7. Thread B gets scheduled, having been woken, but finds the queue still empty.

For performance reasons, the POSIX API allows the OS to wake up your thread even if the condition has not been fulfilled (that's called a spurious wakeup).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!