c++ - atomic_compare_exchange 大于而不是等于?

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

C++11 对 atomic variables 有一个“比较和交换”操作.

语义是:

Atomically compares the value pointed to by obj with the value pointed to by expected, and if those are equal, replaces the former with desired (performs read-modify-write operation). Otherwise, loads the actual value pointed to by obj into *expected (performs load operation).

我想做同样的事情,但不是在值相等时设置 *obj,而是在一个大于另一个时设置它(假设我们谈论的是有序类型)。

这是否以某种方式得到支持?也许可以通过一些 hack 来实现?

注意:CAS 循环对我不起作用,因为我比较的两个值都可能在非原子操作之间发生变化。

最佳答案

我认为您误解了比较和交换/交换的工作原理:基本思想是查看当前值后您可以计算出一些相应的新值 - 然后您尝试更新。如果它成功了 - 很好 - 继续你需要做的任何事情,但如果它失败了,那就重新开始:查看其他线程放入其中的新值,并考虑你现在需要的值。

I want it to be set when one is greater-than the other (assume we're talking about an ordered type).

所以说你想存储 11,但前提是现有值仍然原子小于 11。你不会找到直接执行此操作的指令,但你可以使用现有的比较和交换轻松地执行此操作:

int target_value = 11;
do {
    int snapped_x = x;
    if (snapped_x >= target_value)
        what do you want to do instead?
} while (!compare_and_swap(x, snapped_x, target_value));
         // ...or whatever your exact calling convention is...

你仍然会得到你想要的行为,只是失败率/旋转率可能更高....

关于c++ - atomic_compare_exchange 大于而不是等于?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17701401/

相关文章:

macos - Mac 中找不到包 'libcrypto'

c++ - 了解原子变量和操作

java - 以线程安全的方式填充映射并将该映射从后台线程传递给另一个方法?

c++ - 当您调用 new[] 为 N 个整数分配一个数组时,是否保证该数组将按顺序分配到物理内存中?

c++ - 嵌套 Boost.Assignment `map_list_of`

c++ - 如何在C++中chartdirector的XY图表中的自定义位置添加标签?

java - 将 volatile 与 "AtomicInteger"一起使用可以保证线程安全吗?

c++ - 如何在 QwtPlot 上设置固定数量的刻度

c++ - 具有可变参数的虚方法

c++ - gtkmm 管理/添加 vs 智能指针 :