gpt4 book ai didi

c++11 - 去原子和内存顺序

转载 作者:IT王子 更新时间:2023-10-29 01:50:21 25 4
gpt4 key购买 nike

我正在从 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,它似乎按预期工作,但速度慢了几个数量级,我想知道这些专门的操作对性能有多大影响。

  • 来 self 所附链接的更多信息

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++ 中拥有的控件完全不同——您的帖子中没有直接翻译 C++ 功能。这是 Go 作者深思熟虑的设计决定 - Go 的座右铭是 Do not communicate by sharing memory; instead, share memory by communicating .

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

关于c++11 - 去原子和内存顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28924132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com