multithreading - 乱序执行和重新排序 : can I see what after barrier before the barrier?

标签 multithreading concurrency memory-model

根据维基百科:内存屏障,也称为 membar、内存栅栏或栅栏指令,是一种栅栏指令,它导致中央处理单元 (CPU) 或编译器对在屏障指令。 这通常意味着在屏障之前发出的操作保证在屏障之后发出的操作之前执行。

通常,文章谈论类似(我将使用监视器而不是 membars):

class ReadWriteExample {                                          
    int A = 0;    
    int Another = 0;                                                

    //thread1 runs this method                                    
    void writer () {                                              
      lock monitor1;   //a new value will be stored            
      A = 10;          //stores 10 to memory location A        
      unlock monitor1; //a new value is ready for reader to read
      Another = 20; //@see my question  
    }                                                             

    //thread2 runs this method                                    
    void reader () {                                              
      lock monitor1;  //a new value will be read               
      assert A == 10; //loads from memory location A
      print Another //@see my question           
      unlock monitor1;//a new value was just read              
   }                                                              
}       

但我想知道编译器或 cpu 是否有可能以代码打印 20 的方式对周围的事物进行洗牌?我不需要保证。

IE。根据定义,在屏障之前发出的操作不能被编译器下推,但是在屏障之后发出的操作是否可能偶尔会在屏障之前看到? (只是一个概率)

谢谢

最佳答案

我在下面的回答仅针对 Java 的内存模型。确实不能为所有语言做出答案,因为每种语言可能会以不同的方式定义规则。

But I wonder is it possible that compiler or cpu will shuffle the things around in a such way that code will print 20? I don't need guarantee.



您的回答似乎是“A = 20 的商店是否可以在解锁监视器上方重新排序?”

答案是是的 , 有可能。如果您查看 JSR 166 Cookbook ,显示的第一个网格解释了重新排序的工作原理。

在您的 writer如果第一个操作是 MonitorExit第二个操作是 NormalStore .网格解释说,是的,这个序列被允许重新排序。

这被称为 Roach Motel排序,即内存访问可以移入同步块(synchronized block)但不能移出

那另一种语言呢?好吧,这个问题太宽泛了,无法回答所有问题,因为每个问题都可能以不同的方式定义规则。如果是这种情况,您将需要完善您的问题。

关于multithreading - 乱序执行和重新排序 : can I see what after barrier before the barrier?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29519821/

相关文章:

java - 该等待/通知代码性能异常

c - 将大量线程固定到单个 CPU 会导致所有内核的利用率激增

python - 为什么我的 python 代码仅在多线程时不起作用 - Tkinter

concurrency - N皇后问题的Racket代码并行运行

.net - 在单独的进程中运行 .net 代码

c# - 内存模型和线程池

c++ - 在发布序列中使用原子读-修改-写操作

java - 将线程安全委托(delegate)给 ConcurrentMap 和 AtomicInteger

java - 线程已停止但仍在以错误的 boolean 值运行(Java)

synchronization - 线程同步: How to guarantee visibility of writes