刚刚在看 Hans Boehm 的大作 Threads Cannot be Implemented as a Library ,算是对这个问题有了一个总结,reorder 来自两个方面:
<br>
<br>• Compilers may reorder memory operations if that doesn’t violate intra-thread dependencies. Each pair of actions in the above threads could be reordered, since doing so does not change the meaning of each thread, taken in isolation. And performing loads early may result in a better instruction schedule, potentially resulting in performance improvements. (Cf. [2].)
<br>
<br>• The hardware may reorder memory operations based on similar constraints. Nearly all common hardware, e.g. X86 processors, may reorder a store followed by a load[17]. Generally a store results immediately in a write-buffer entry, which is later written to a coherent cache, which would then be visible to other threads.
<br>
<br>好了,相信这个够全面了。
<br>
对,就是这样。不过前几天一个比较资深的工程师提醒了我:现在的x86 CPU 本身就有乱序执行的,所以即便从汇编语句中看不出端倪,也仍然可能产生问题。如果要真的解决,还要了解得更加详细。但是即便我再去仔细钻研了CPU 的文档,得到的结论仍然可能是片面的。所以我决定放弃这个努力,也难怪现在 C++ 社群里面有那么多人在作 multithread memory model 方面的工作,没有它,程序员根本无从准确预测多线程程序的行为。