C++11 对 atomic variables 有一个“比较和交换”操作.
语义是:
Atomically compares the value pointed to by
obj
with the value pointed to byexpected
, and if those are equal, replaces the former withdesired
(performs read-modify-write operation). Otherwise, loads the actual value pointed to byobj
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/