看到各种锁相关的问题和(几乎)总是发现'循环,因为虚假的唤醒'术语1我想知道,有没有人经历过这样的唤醒(假设一个体面的硬件/软件环境为例)?
我知道“虚假”这个词的意思是没有明显的原因,但这种事件的原因是什么呢?
(1注意:我不是在质疑循环实践。)
编辑:一个辅助问题(对于那些喜欢代码示例的人):
如果我有下面的程序,我运行它:
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();
}
}
}
我能做些什么来唤醒这个等待,而不是永远等待一个随机事件?
回答标题中的问题-是的!这种情况确实会发生。虽然维基上的文章提到了很多关于虚假唤醒的事情,但我遇到的一个很好的解释是
Just think of it... like any code, thread scheduler may experience temporary blackout due to something abnormal happening in underlying hardware / software. Of course, care should be taken for this to happen as rare as possible, but since there's no such thing as 100% robust software it is reasonable to assume this can happen and take care on the graceful recovery in case if scheduler detects this (eg by observing missing heartbeats).
Now, how could scheduler recover, taking into account that during blackout it could miss some signals intended to notify waiting threads? If scheduler does nothing, mentioned "unlucky" threads will just hang, waiting forever - to avoid this, scheduler would simply send a signal to all the waiting threads.
This makes it necessary to establish a "contract" that waiting thread can be notified without a reason. To be precise, there would be a reason - scheduler blackout - but since thread is designed (for a good reason) to be oblivious to scheduler internal implementation details, this reason is likely better to present as "spurious".
我读了这个来源的答案,发现它足够合理。也读
Java中的虚假唤醒以及如何避免它们。
附注:上面的链接是我的个人博客,上面有关于虚假唤醒的更多细节。
回答标题中的问题-是的!这种情况确实会发生。虽然维基上的文章提到了很多关于虚假唤醒的事情,但我遇到的一个很好的解释是
Just think of it... like any code, thread scheduler may experience temporary blackout due to something abnormal happening in underlying hardware / software. Of course, care should be taken for this to happen as rare as possible, but since there's no such thing as 100% robust software it is reasonable to assume this can happen and take care on the graceful recovery in case if scheduler detects this (eg by observing missing heartbeats).
Now, how could scheduler recover, taking into account that during blackout it could miss some signals intended to notify waiting threads? If scheduler does nothing, mentioned "unlucky" threads will just hang, waiting forever - to avoid this, scheduler would simply send a signal to all the waiting threads.
This makes it necessary to establish a "contract" that waiting thread can be notified without a reason. To be precise, there would be a reason - scheduler blackout - but since thread is designed (for a good reason) to be oblivious to scheduler internal implementation details, this reason is likely better to present as "spurious".
我读了这个来源的答案,发现它足够合理。也读
Java中的虚假唤醒以及如何避免它们。
附注:上面的链接是我的个人博客,上面有关于虚假唤醒的更多细节。