去原子和内存顺序

Go atomic and memory order

我正在从 c++11 移植一个无锁队列,我遇到了诸如

auto currentRead = writeIndex.load(std::memory_order_relaxed);

在某些情况下 std::memory_order_releasestd::memory_order_aqcuire 在 c11 中,上面的等价物也类似于

unsigned long currentRead = atomic_load_explicit(&q->writeIndex,memory_order_relaxed);

描述了那些的意思here

在 go 中是否有类似的东西,或者我只是使用类似的东西

var currentRead uint64 = atomic.LoadUint64(&q.writeIndex)

移植后我进行了基准测试并仅使用 LoadUint64 它似乎按预期工作但速度慢了几个数量级我想知道这些专门的操作对性能有多大影响。

memory_order_relaxed:Relaxed operation: there are no synchronization or ordering constraints, only atomicity is required of this operation.

memory_order_consume:A load operation with this memory order performs a consume operation on the affected memory location: no reads in the current thread dependent on the value currently loaded can be reordered before this load. This ensures that writes to data-dependent variables in other threads that release the same atomic variable are visible in the current thread. On most platforms, this affects compiler optimizations only.

memory_order_acquire:A load operation with this memory order performs the acquire operation on the affected memory location: no memory accesses in the current thread can be reordered before this load. This ensures that all writes in other threads that release the same atomic variable are visible in the current thread.

memory_order_release:A store operation with this memory order performs the release operation: no memory accesses in the current thread can be reordered after this store. This ensures that all writes in the current thread are visible in other threads that acquire or the same atomic variable and writes that carry a dependency into the atomic variable become visible in other threads that consume the same atomic.

你需要阅读The Go Memory Model

您会发现 Go 与您在 C++ 中拥有的控件完全不同——在您的 post 中没有 C++ 功能的直接翻译。这是 Go 作者深思熟虑的设计决定 - Go 的座右铭是 Do not communicate by sharing memory; instead, share memory by communicating.

假设标准的 go 通道不足以满足你的需求,你将有两种选择来访问内存,是否使用 sync/atomic 中的工具,以及你是否需要使用与否取决于仔细阅读 Go 内存模型和分析你的代码,只有你才能做到。