[英]Does golang atomic.Load have a acquire semantics?
Given a c++ code snip:给定一个 C++ 代码片段:
int a = 0;
atomic<int> b{0};
Thread 1
a = 1;
b.store(1,memory_order_release);
Thread 2
while(!b.load(memory_order_acquire));
assert(a==1);
We know the assert never fire.我们知道断言永远不会触发。
At the other hand, golang atomic.Store uses xchg instruction which implicts memory-barrier, so it can result in memory_order_release semantics as c++11.另一方面,golang atomic.Store使用 xchg 指令暗示内存屏障,因此它可以导致 memory_order_release 语义为 c++11。
//go:noescape
func Store(ptr *uint32, val uint32)
TEXT runtime∕internal∕atomic·Store(SB), NOSPLIT, $0-12
MOVQ ptr+0(FP), BX
MOVL val+8(FP), AX
XCHGL AX, 0(BX)
RET
However, the implementation of atomic.Load is pure go code, which means just mov instruction when assembly.但是atomic.Load的实现是纯 go 代码,也就是说汇编时只是 mov 指令。
//go:nosplit
//go:noinline
func Load(ptr *uint32) uint32 {
return *ptr
}
So, does golang atomic.Load have a acquire semantics?那么,golang atomic.Load 有获取语义吗?
If do how it works, and if not how to insure memory-ordering or make a=1 visible?如果它是如何工作的,如果不是如何确保内存排序或使 a=1 可见?
On strongly ordered architectures like x86/amd64, acquire load and release store are just regular loads and stores.在 x86/amd64 等强有序架构上,获取加载和释放存储只是常规加载和存储。 To make them atomic you need to ensure the memory is aligned to the operand size (automatic in Go), and that the compiler doesn't re-order them in incompatible ways, or optimize them away (eg reuse a value in a register instead of reading it from memory.)
为了使它们具有原子性,您需要确保内存与操作数大小对齐(在 Go 中是自动的),并且编译器不会以不兼容的方式对它们重新排序,或者将它们优化掉(例如重用寄存器中的值)从记忆中读取它。)
The Go atomic Load* and Store* functions are sequentially consistent. Go 原子 Load* 和 Store* 函数顺序一致。 This is a stronger form of memory ordering that requires memory fences (or instructions that have an implicit memory fence) even on x86/amd64.
这是一种更强的内存排序形式,即使在 x86/amd64 上也需要内存栅栏(或具有隐式内存栅栏的指令)。
Quoting rsc:引用 rsc:
Go's atomics guarantee sequential consistency among the atomic variables (behave like C/C++'s seqconst atomics), and that you shouldn't mix atomic and non-atomic accesses for a given memory word.
Go 的原子保证原子变量之间的顺序一致性(行为类似于 C/C++ 的 seqconst 原子),并且你不应该对给定的内存字混合原子和非原子访问。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.