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

标签 c++ multithreading c++11 atomic compare-and-swap

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/

相关文章:

c++ - C++中 'this'指针的用例

java - 从可运行类更新 swing JEditorPane

java - 在新线程中有监听器

c++ - 在 C++11 中将成员函数指定为回调

c++ - 我的 2D 迷宫解算器无限递归并且出现堆栈溢出 - 为什么?

当到达字符串末尾时,C++ getline 导致段错误

c++ - 为什么 Linux 将干净的 MAP_ANONYMOUS 内存页转储到核心转储?

c++ - 为什么模板只能在头文件中实现?

c++ - 在 c++0x 中使用 __thread

c++ - 为什么我的模板不接受初始化列表