Java中的虚假唤醒真的发生了吗? [英] Do spurious wakeups in Java actually happen?

查看:460
本文介绍了Java中的虚假唤醒真的发生了吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看到各种与锁相关的问题,并且(几乎)总是找到'因为虚假的唤醒而导致的循环'术语 1 我想,有没有人经历过这样的唤醒(假设一个像样的硬件/软件环境)例如)?

Seeing various locking related question and (almost) always finding the 'loop because of spurious wakeups' terms1 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?

1 注意:我不是在质疑循环练习。)

(1 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();
        }
    }
}

我该怎么做才能唤醒这个等待虚假而不等待永远的随机事件?

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信号将产生虚假唤醒。

The pthread_cond_wait() function in Linux is implemented using the futex system call. Each blocking system call on Linux returns abruptly with EINTR when the process receives a signal. ... pthread_cond_wait() can't restart the waiting because it may miss a real wakeup in the little time it was outside the futex system call. This race condition can only be avoided by the caller checking for an invariant. A POSIX signal will therefore generate a spurious wakeup.

摘要:如果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中的虚假唤醒真的发生了吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆