gpt4 book ai didi

c++ - 什么时候应该使用 std::atomic_compare_exchange_strong?

转载 作者:可可西里 更新时间:2023-11-01 16:37:39 31 4
gpt4 key购买 nike

C++11 中有两个原子 CAS 操作:atomic_compare_exchange_weakatomic_compare_exchange_strong

根据 cppreference :

The weak forms of the functions are allowed to fail spuriously, that is, act as if *obj != *expected even if they are equal. When a compare-and-exchange is in a loop, the weak version will yield better performance on some platforms. When a weak compare-and-exchange would require a loop and a strong one would not, the strong one is preferable.

以下是使用版本的例子,我认为:

do {
expected = current.value();
desired = f(expected);
} while (!current.atomic_compare_exchange_weak(expected, desired));

有人可以举一个例子,其中比较和交换不在循环中,以便 strong 版本更可取吗?

最佳答案

atomic_compare_exchange_XXX 函数用观测值更新它们的“预期”参数,因此您的循环与:

expected = current;
do {
desired = f(expected);
} while (!current.atomic_compare_exchange_weak(expected, desired));

如果期望值独立于期望值,则此循环变为:

desired = ...;
expected = current;
while (current.atomic_compare_exchange_weak(expected, desired))
;

让我们添加一些语义。假设有多个线程同时运行。在每种情况下,desired 都是当前线程的非零 ID,current 用于提供互斥以确保某个线程执行清理任务。我们并不真正关心是哪一个,但我们希望确保某个线程获得访问权限(也许其他线程可以通过从 current 中读取它的 ID 来观察获胜者)。

我们可以通过以下方式实现所需的语义:

expected = 0;
if (current.atomic_compare_exchange_strong(expected, this_thread)) {
// I'm the winner
do_some_cleanup_thing();
current = 0;
} else {
std::cout << expected << " is the winner\n";
}

在这种情况下,atomic_compare_exchange_weak 需要一个循环来实现与 atomic_compare_exchange_strong 相同的效果,因为可能会出现虚假故障:

expected = 0;
while(!current.atomic_compare_exchange_weak(expected, this_thread)
&& expected == 0))
;
if (expected == this_thread) {
do_some_cleanup_thing();
current = 0;
} else {
std::cout << expected << " is the winner\n";
}

该标准表明,在这种情况下,实现可以为 atomic_compare_exchange_strong 提供比使用 ..._weak 循环更高效的代码(§29.6.5/25 [atomics.types .operations.req]).

关于c++ - 什么时候应该使用 std::atomic_compare_exchange_strong?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17914630/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com