简体   繁体   English

可见性和订购之间的关系/区别是什么?

[英]What's the relationship/difference between Visibility and Ordering?

So far as I know, Visibility deals with under what condition can a thread observe/see the update to shared variable(s) by another thread. 据我所知,Visibility处理线程在什么条件下可以观察/看到另一个线程对共享变量的更新。 Even single-processor system can suffer from Visibility issue. 即使是单处理器系统也会遇到可见性问题。 While Ordering deals with in what sequence does a thread see memory operations performed by another run in another CPU. Ordering以什么顺序处理线程看到另一个CPU中另一个运行执行的内存操作。 Single-processor system does NOT suffer from Ordering issue. 单处理器系统不会受到订购问题的影响。 But, I felt that sometimes so-called Ordering issue can be interpreted with the concept of Visibility,e,g. 但是,我觉得有时所谓的订购问题可以用可见性的概念来解释,例如。

//Thread1 runs
int data;
boolean ready;
void method1(){
  data=1;
  ready=true;
}

//Thread2 runs
void method2(){
  if(ready){
  System.out.print(data);
  }
}

If the output of the above program was "0"(rather than "1"), we can say that there was an Ordering issue(ie Reordering)---the write to ready appeared to be occurred before the write to data . 如果上述程序的输出为“0”(而不是“1”),我们可以说有一个Ordering问题(即重新排序)---写入就绪 似乎是在写入数据之前发生的。 However, I think we can also interpret this output as a result of Visibility: Thread2 first saw the update to ready by Thread1, and then data ,possibly due to Store Buffer flush to CPU Cache, And if the print(data) was executed before Thread2 saw update to data , then we got the output "0". 但是,我认为我们也可以将此输出解释为Visibility的结果:Thread2首先看到Thread1更新为ready ,然后是数据 ,可能是由于Store Buffer刷新到CPU Cache,如果print(data)之前执行了Thread2看到了对数据的更新,然后我们得到了输出“0”。 Taking this into account, I just wonder what's is the difference/relationship between Visibility and Ordering? 考虑到这一点,我只是想知道Visibility和Ordering之间的区别/关系是什么?

Yes, ordering and visibility are related issues. 是的,订购和可见性是相关问题。

  • Visibility is about whether / when one thread sees the results of memory writes performed by another thread 可见性是关于一个线程是否/何时看到另一个线程执行的内存写入的结果

  • Ordering is about whether the order in which updates are seen by the second thread matches the (program) order in which the first thread wrote them. 排序是关于第二个线程看到更新的顺序是否与第一个线程写入它们的(程序)顺序相匹配。

The Java memory model doesn't directly address the ordering of writes. Java内存模型不直接解决写入顺序。 Any constraints on order are (as you hypothesize) a consequence of the visibility rules: these are specified in the JLS. 订单的任何约束都是(如您所假设的)可见性规则的结果:这些约束在JLS中指定。 This includes the case where you use volatile variables to effectively inhibit reordering. 这包括使用volatile变量来有效抑制重新排序的情况。

It is also worth noting that the reordering of writes (from the perspective of a second thread) can happen whenever the JLS memory model does not require visibility. 值得注意的是,只要JLS内存模型不需要可见性,就可以发生写入的重新排序(从第二个线程的角度来看)。 Correct synchronization will guarantee visibility at the point of synchronization. 正确的同步将保证同步点的可见性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM