C++ atomic memory model和Arm实现方式

微信公众号: mindshare思享




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构架基础。

C++ atomic 变量和操作


§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.


一个例子,


C++ memory model

§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)







Armv8.1-A构架实现


在不同的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++ lock free 编程



结语

只有充分理解C++的memory model,和理解它在具体CPU的实现,才能更正常和有效的使用它们。

本文作为一个概述,有时间再写更具体的内容。




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构架基础。

C++ atomic 变量和操作


§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.


一个例子,


C++ memory model

§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)







Armv8.1-A构架实现


在不同的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++ lock free 编程



结语

只有充分理解C++的memory model,和理解它在具体CPU的实现,才能更正常和有效的使用它们。

本文作为一个概述,有时间再写更具体的内容。


猜你喜欢

转载自blog.csdn.net/weixin_39366778/article/details/80495099