C++ atomic memory model 和 Arm構架實現
C++的memory model是軟體工程師比較難理解的一部分,因為深入理解它需要有一定的CPU構架和微構架的知識基礎。
C++作為高級語言本身應該和CPU的硬體是無關的,但是為了使一些原子(atomic)操作能夠在CPU更有效率的運行,避免因為原子操作帶來的memory ordering要求對系統性能的影響,C++的原子操作會帶有memory ordering的限定。
本文將通過圖表的方式介紹C++的atomic memory ordering和其在Arm構架上的實現。
閱讀本文需要有些C++atomic和CPU構架基礎。
§std::atomic
§The class to use when writing lock-free code!
§A template wrapper around various types, providing access that is:
Atomic – reads and writes are done as a whole.
Ordered with respect to other accesses to the variable (or others).
§Depending on the target platform, operations can be lock-free, or protected by a mutex.
一個例子,
§Memory access ordering is specified by std::memory_order _...
§Operations can limit reordering around themselves for operations with the ordinary variables and operations with other atomic variables.
下面是對每個memory ordering specifier (std::memory_order _...)限定的memory ordering的具體解釋,綠色箭頭表示允許的re-order,紅色表示不允許的re-order. (圖表原創,all copy rights are reserved)
在不同的Arm構架上,C++的atomic的實現會有所不同。
在v7-A上是通過LDREX/STREX + DMB來實現的,在V8-A上通過LDREX/STREX + DMB和Load-acquire (LDRA), store-release(STRL)指令來實現。
在Armv8.1-A上增加了atomic指令,這些指令本身也可以帶acquire,release的memory ordering限定。
下面是Armv8.1-A的實現方法。
只有充分理解C++的memory model,和理解它在具體CPU的實現,才能更正常和有效的使用它們。
本文作為一個概述,有時間再寫更具體的內容。