问题描述
看到各种与锁定相关的问题,并且(几乎)总是找到由于虚假唤醒而导致的循环"术语我想知道,有没有人经历过这种唤醒(假设硬件/软件环境不错)例如)?
Seeing various locking related question and (almost) always finding the 'loop because of spurious wakeups' terms I wonder, has anyone experienced such kind of a wakeup (assuming a decent hardware/software environment for example)?
我知道术语虚假"的意思是没有明显的原因,但这种事件的原因是什么?
I know the term 'spurious' means no apparent reason but what can be the reasons for such kind of an event?
( 注意:我不是在质疑循环实践.)
( Note: I'm not questioning the looping practice.)
一个帮助问题(对于那些喜欢代码示例的人):
A helper question (for those who like code samples):
如果我有以下程序,并运行它:
If I have the following program, and I run it:
public class Spurious {
public static void main(String[] args) {
Lock lock = new ReentrantLock();
Condition cond = lock.newCondition();
lock.lock();
try {
try {
cond.await();
System.out.println("Spurious wakeup!");
} catch (InterruptedException ex) {
System.out.println("Just a regular interrupt.");
}
} finally {
lock.unlock();
}
}
}
我能做些什么来虚假地唤醒这个 await
而不永远等待一个随机事件?
What can I do to wake this await
up spuriously without waiting forever for a random event?
推荐答案
维基百科关于虚假唤醒的文章 有这个花絮:
The Wikipedia article on spurious wakeups has this tidbit:
Linux 中的pthread_cond_wait()
函数是使用futex
系统调用实现的.当进程接收到信号时,Linux 上的每个阻塞系统调用都会突然返回 EINTR
.... pthread_cond_wait()
无法重新开始等待,因为它可能会在 futex
系统调用之外的一小段时间内错过真正的唤醒.这种竞争条件只能通过调用者检查不变量来避免.因此,POSIX 信号会产生虚假唤醒.
总结:如果 Linux 进程收到信号,它的等待线程将各自享受良好的虚假唤醒.
Summary: If a Linux process is signaled its waiting threads will each enjoy a nice, hot spurious wakeup.
我买了.与通常给出的通常含糊的这是为了性能"的原因相比,这更容易吞咽.
I buy it. That's an easier pill to swallow than the typically vague "it's for performance" reason often given.
这篇关于Java 中的虚假唤醒真的发生了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!