关于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是不正确的。

相关推荐
geovindu5 分钟前
CSharp: Dijkstra Algorithms
开发语言·后端·算法·c#
XR12345678812 分钟前
食品饮料与制药行业GMP合规网络建设:无尘车间的网络不能成为污染源
开发语言·网络·php
学逆向的30 分钟前
汇编——位运算
开发语言·汇编·算法·网络安全
zhangjw3438 分钟前
第29篇:Java伪共享与对象分配:并发性能优化的关键
java·开发语言·性能优化
知无不研1 小时前
缺省参数与缺省函数的区别
c++·语法
Java面试题总结1 小时前
Python 开发技巧 · 高级装饰器 —— 从基础到工业级实战
开发语言·python
liulilittle2 小时前
Exhaustive drift-fix simulation V2 — KCC on shared-bottleneck wired path.
开发语言·网络·python·tcp/ip·计算机网络·信息与通信·通信
名字还没想好☜3 小时前
Go error 处理:errors.Is/As 与错误包装
开发语言·后端·golang·go·错误处理
红糖奶茶3 小时前
Python 中 while 循环计数异常的常见原因分析与正确搓搓
开发语言·python
Lucky_Turtle3 小时前
【论文写作】PDF图片不清晰,打印生成PDF空白大,PDF字体嵌入
开发语言·pdf·c#