关于std::memory_order_consume

原文:https://preshing.com/20140709/the-purpose-of-memory_order_consume-in-cpp11/

翻译:C++11中memory_order_consume的目的

https://blog.csdn.net/netyeaxi/article/details/80718781

文章中有这样一个例子:

复制代码
g = Guard.load(memory_order_consume);
if (g != nullptr)
    p = *g;

既然g已经表明了代码级别的依赖,为什么还需要memory_order_consume,而不可以直接memory_order_relaxed呢?

搜了一下这里有个解释,但是它似乎没有说清楚:https://stackoverflow.com/questions/38280633/c11-the-difference-between-memory-order-relaxed-and-memory-order-consume

其实也比较简单,先看一下memory_order_release的规则(中英文对照方便理解):https://en.cppreference.com/w/cpp/atomic/memory_order

有此内存定序的存储操作进行释放操作:当前线程中的读或写不能被重排到此存储之后。

  1. 当前线程的所有写入,可见于获得该同一原子变量的其他线程(见下方释放-获得定序)
  2. 并且对该原子变量的带依赖写入变得对于其他消费同一原子对象的线程可见(见下方释放-消费定序)。

A store operation with this memory order performs the release operation: no reads or writes in the current thread can be reordered after this store.

  1. All writes in the current thread are visible in other threads that acquire the same atomic variable (see Release-Acquire ordering below)
  2. writes that carry a dependency into the atomic variable become visible in other threads that consume the same atomic (see Release-Consume ordering below).

注意第二条:在其他线程,使用consume能保证该原子变量的带依赖写入(文中的g)可见。换言之relaxed不能保证这一点。

也就是:

复制代码
Payload = 42;
Guard.store(&Payload, memory_order_release);

在另一个线程看起来可能是:

复制代码
Guard.store(&Payload, memory_order_release);
Payload = 42;

另外我们也能得到这样的结论:只使用memory_order_release,而不配合使用acquire或consume或其他更严格约束的话,对其他线程来说是没有意义的。

再推而广之,所有的memory_order都要在多个线程配合使用,才能影响变量在线程之间的可见性。根据这一点,也能理解为什么relaxed是不正确的。

相关推荐
badhope1 小时前
Mobile-Skills:移动端技能可视化的创新实践
开发语言·人工智能·git·智能手机·github
码云数智-园园3 小时前
微服务架构下的分布式事务:在一致性与可用性之间寻找平衡
开发语言
C++ 老炮儿的技术栈3 小时前
volatile使用场景
linux·服务器·c语言·开发语言·c++
hz_zhangrl3 小时前
CCF-GESP 等级考试 2026年3月认证C++一级真题解析
开发语言·c++·gesp·gesp2026年3月·gespc++一级
Liu628883 小时前
C++中的工厂模式高级应用
开发语言·c++·算法
IT猿手3 小时前
基于控制障碍函数的多无人机编队动态避障控制方法研究,MATLAB代码
开发语言·matlab·无人机·openclaw·多无人机动态避障路径规划·无人机编队
AI科技星3 小时前
全尺度角速度统一:基于 v ≡ c 的纯推导与验证
c语言·开发语言·人工智能·opencv·算法·机器学习·数据挖掘
sunwenjian8864 小时前
Java进阶——IO 流
java·开发语言·python
波特率1152004 小时前
const关键字与函数的重载
开发语言·c++·函数重载
FL16238631294 小时前
[C#][winform]segment-anything分割万物部署onnx模型一键抠图演示
开发语言·c#