c – 将不同线程中同一位置的两次轻松写入总是以其他线程以相同的顺序看到?

前端之家收集整理的这篇文章主要介绍了c – 将不同线程中同一位置的两次轻松写入总是以其他线程以相同的顺序看到?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在x86体系结构中,存储到同一内存位置的总顺序,例如参见 this video.C11内存模型有哪些保证?

更准确地说,

-- 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怎么办?

解决方法

不,这样的结果是不允许的. §1.10[intro.multithread] / p8,18(引用N3936 / C 14; N3337 / C 11第6和16段中的相同文字):

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 ]

猜你在找的C&C++相关文章