POSIX 条件变量 VS Win32 事件对象(关于虚假唤醒问题)

POSIX condition variables VS Win32 Event Objects (about spurious wakeup problem)

在POSIX中,由于“虚假唤醒”问题,程序员在检查条件时被迫使用while()而不是if

我认为虚假唤醒是一个不直观且令人困惑的问题,但我认为这是一个不可避免的问题。

最近发现win32的事件对象没有“虚假唤醒”的问题

为什么POSIX系统和其他系统仍然使用存在“虚假唤醒”问题的条件变量? (尽管这可以解决?)

你问:

Why POSIX system and other systems still use condition variable which has "spurious wakeup" problem? (despite this can be solved?)

基本上,它比替代方案更快。

POSIX.1-2017 治疗 pthread_cond_broadcastpthread_cond_signal 的基本原理部分特别说明了 "Multiple Awakenings by Condition Signal":

While [the "spurious wakeup"] problem could be resolved, the loss of efficiency for a fringe condition that occurs only rarely is unacceptable, especially given that one has to check the predicate associated with a condition variable anyway. Correcting this problem would unnecessarily reduce the degree of concurrency in this basic building block for all higher-level synchronization operations.

添加了重点。

文中进一步指出,强制“围绕条件等待的谓词测试循环”是一种比替代方案更健壮的编码实践,因为应用程序必然会容忍来自代码中其他地方的多余广播和信号。