本文介绍了golang atomic.Load是否具有获取语义?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个c ++代码片段:

Given a c++ code snip:

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.

另一方面,golang atomic.Store 使用xchg指令隐含了内存屏障,因此它会导致c_11的memory_order_release语义.

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.

//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

但是,是纯粹的go代码,这意味着在汇编时只是mov指令.

However, the implementation of atomic.Load is pure go code, which means just mov instruction when assembly.

//go:nosplit
//go:noinline
func Load(ptr *uint32) uint32 {
    return *ptr
}

那么,golang atomic.Load是否具有获取语义?
如果它是如何工作的,是否不能确保内存顺序或使a = 1可见?

So, does golang atomic.Load have a acquire semantics?
If do how it works, and if not how to insure memory-ordering or make a=1 visible?

推荐答案

在x86/amd64之类的有序结构上,获取加载和发布存储只是常规加载和存储.为了使它们原子化,您需要确保内存与操作数大小对齐(在Go中是自动的),并且编译器不会以不兼容的方式对它们进行重新排序,也不会对其进行优化(例如,重新使用寄存器中的值)从内存中读取数据.)

On strongly ordered architectures like x86/amd64, acquire load and release store are just regular loads and stores. 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 (e.g. reuse a value in a register instead of reading it from memory.)

Go原子Load *和Store *函数顺序一致.这是一种更强大的内存排序形式,甚至在x86/amd64上也需要内存围栏(或具有隐式内存围栏的指令).

The Go atomic Load* and Store* functions are sequentially consistent. This is a stronger form of memory ordering that requires memory fences (or instructions that have an implicit memory fence) even on x86/amd64.

引用rsc:

这篇关于golang atomic.Load是否具有获取语义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!