更准确地说,
-- Initially -- std::atomic<int> x{0}; -- Thread 1 -- x.store(1,std::memory_order_release); -- Thread 2 -- x.store(2,std::memory_order_release); -- Thread 3 -- int r1 = x.load(std::memory_order_acquire); int r2 = x.load(std::memory_order_acquire); -- Thread 4 -- int r3 = x.load(std::memory_order_acquire); int r4 = x.load(std::memory_order_acquire);
将结果r1 == 1,r2 == 2,r3 == 2,r4 == 1被允许(在某些架构以外的x86)?如果我要用std :: memory_order_relaxed替换所有的memory_order怎么办?
解决方法
8 All modifications to a particular atomic object M occur in some
particular total order,called the modification order of M.18 If a value computation A of an atomic object M happens before a
value computation B of M,and A takes its value from a side effect X
on M,then the value computed by B shall either be the value stored by
X or the value stored by a side effect Y on M,where Y follows X in
the modification order of M. [ Note: This requirement is kNown as
read-read coherence. —end note ]
在你的代码中有两个副作用,而p8它们以一些特定的总顺序发生.在线程3中,用于计算存储在r1中的值的值计算发生在r2之前,因此给定r1 == 1和r2 == 2,我们知道由线程1执行的存储先于线程2执行的存储x的修改顺序.在这种情况下,线程4无法观察到r3 == 2,r4 == 1,而不会碰到p18.这与使用的memory_order无关.
p21中的一个注释(N3337中的p19)是相关的:
[ Note: The four preceding coherence requirements effectively
disallow compiler reordering of atomic operations to a single object,
even if both operations are relaxed loads. This effectively makes the
cache coherence guarantee provided by most hardware available to C++
atomic operations. —end note ]
原文地址:https://www.jb51.cc/c/112695.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。