共享变量的陈旧值 [英] Stale value of Shared variable

查看:88
本文介绍了共享变量的陈旧值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在实践中阅读并发时,我读到了


否可见性证明了
同步程序的不足之处导致令人惊讶的结果:陈旧的数据。当
读者线程检查准备就绪时,它可能会看到过时的值。除非每次访问变量时都使用
同步,否则可能会看到
该变量的陈旧值。更糟糕的是,过期是
并非全是或全无:一个线程可以看到一个变量
的最新值,但是第一个写入的另一个变量的陈旧值




  public class NoVisibility {
private static boolean ready;
private static int number;
私有静态类ReaderThread扩展线程{
public void run(){
while(!ready)
Thread.yield();
System.out.println(number);
}
}
public static void main(String [] args){
new ReaderThread()。start();
number = 42;
ready = true;
}
}

我没有得到陈旧的含义。两个线程共享相同的引用,如何修改一个值永远不会被其他线程看到?

解决方案

它的主要意图是在同一时间设置number = 42和ready = true,但由于它们是按照这个特定的顺序调用的,因此你的ReaderThread存在竞争条件,它可能(可能会)打印出这个数字即使我们真的不想要它。



他们希望你同步这两个被设置在一起的变量。


While reading Concurrency in practice , i read that

No Visibility demonstrate done of the ways that insufficiently synchronized programs can cause surprising results:stale data.When the reader thread examines ready, it may see an out of date value. Unless synchronization isused every time a variable is accessed, it is possible to see a stale value for that variable. Worse, staleness is not all or nothing:a thread can see an upto date value of one variable but a stale value of another variable that was written first

public class NoVisibility {
    private static boolean ready;
    private static int number;
    private static class ReaderThread extends Thread {
    public void run() {
    while (!ready)
    Thread.yield();
    System.out.println(number);
    }
    }
    public static void main(String[] args) {
    new ReaderThread().start();
    number = 42;
    ready = true;
    }
    }

I am not getting meaning of stale. Both threads are sharing the same reference , how can value modified by one will never be or not be visible to other thread?

解决方案

It's saying that in main the intention is to set number=42 and ready=true at the same time, but since they were called in this particular order there is a race condition with your ReaderThread where it could (probably will) print out the number even though we really don't want it to.

They would like you to synchronize those 2 variables being set together.

这篇关于共享变量的陈旧值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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