为什么需要关心内存模型

内存一致性模型 memory consistency model,又叫内存模型。通过内存模型可以知道,什么情况下会发生 reordering。
为什么需要关心内存模型,引用 Linux Document/memory-barriers 中的一段话:

Such enforcement is important because the CPUs and other devices in a systemcan use a variety of tricks to improve performance, including reordering,deferral and combination of memory operations; speculative loads; speculativebranch prediction and various types of caching. Memory barriers are used tooverride or suppress these tricks, allowing the code to sanely control theinteraction of multiple CPUs and/or devices.

硬件需要给软件提供内存一致性模型,用来告诉软件,什么情况下会发生 reorder。
语言是多个硬件系统的抽象,语言需要给 programmer 提供内存一致性模型,告诉 programmer,什么情况下会发生 reorder(编译器的,或者硬件的)

硬件的内存一致性模型

内存一致性模型,store buffer,barrier 的优秀介绍:

内存一致性的文章,可以和上面一篇对照着看:

内存一致性,对照着看:

操作系统的内存一致性模型

linux 源代码中给出的内存一致性模型的介绍:这一篇太低层了,只看了一部分

C++ 的内存模型

gcc 给出的内存模型的介绍:

介绍了 RMW (read-modify-write),以及其中最重要的 RAS(read and swap),并且介绍了如何通过 RAS 实现 lock-free :