[英]C++11 compare and swap acquire/release semantics
Let's assume I have the following code (toy examples): 假设我有以下代码(玩具示例):
std::atomic<K *> data;
K *old_value = NULL;
K *new_value = new K();
if (!data.compare_exchange_strong(old_value, new_value, m1, m2)) {
delete new_value;
}
do_something(old_value);
Or 要么
std::atomic<K *> data;
K *i = data.load(m3);
K *j;
do {
j = i + 1;
} while (data.compare_exchange_weak(i, j, m4, m5);
do_something(j);
What are valid values of m1
, m2
, m3
, m4
and m5
? m1
, m2
, m3
, m4
和m5
有效值是多少? My reading is that all can be std::memory_order_relaxed
as the whole code strongly depends on the result of previous operations (assuming do_something
just uses the pointer and don't alter the global, shared state). 我的理解是,所有代码都可以是
std::memory_order_relaxed
因为整个代码在很大程度上取决于先前操作的结果(假设do_something
仅使用指针而不更改全局共享状态)。 Is my reading correct? 我的阅读正确吗?
This question only makes sense in a multithreaded scenario with a well-defined shared state. 该问题仅在具有明确定义的共享状态的多线程方案中才有意义。 Without knowing what the other thread does, I can only assume that it reads/writes
data
. 在不知道其他线程做什么的情况下,我只能假定它读取/写入
data
。 With just this single point of synchronization, all-relaxed ordering should do just fine. 仅通过此单点同步,所有松弛的排序就可以正常进行。 For any given atomic considered independently of other sync points, operations will still be atomic, and their relative ordering will still be correct.
对于任何独立于其他同步点考虑的给定原子,操作仍将是原子的,并且它们的相对顺序仍将是正确的。
Now, if the shared state consisted of several variables (that's where the "ordering" comes into play), it would be a totally different story; 现在,如果共享状态由多个变量组成(这就是“排序”起作用的地方),那将是一个完全不同的故事。 and you would have to worry about acquire/release/etc.
而您将不得不担心获取/发布/等。 semantics.
语义。 In this case:
在这种情况下:
relaxed
data1
, and thread 2 sets data2
) will be visible to all the other threads in the same order. data1
和线程2设置data2
)所做的更改对于所有其他线程都是相同顺序可见的。 acquire/release
(when used on every read/write, respectively; for different patterns of ordering arguments the first item may become more relaxed) acquire/release
(分别在每次读/写时使用;对于排序参数的不同模式,第一项可能变得更宽松)
seq_cst
(again, when used on every read/write): seq_cst
(同样,在每次读/写时使用):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.