是否有检查前提条件的原子增量,原子值是否小于指定值? [英] Is there atomic increment with the check preconditions, that the atomic value was less than the specified value?

查看:297
本文介绍了是否有检查前提条件的原子增量,原子值是否小于指定值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在增加值之前,在检查前提条件中,在新的标准C ++原子增量操作中,原子值是否小于指定值?

Is in the new standard C++ atomic increment operation with the check preconditions before the incremented the value, that the atomic value was less than the specified value?

比下面的代码更容易和更快吗?

Can I do it easier and faster than the following code?

int atomic_inc(std::atomic_int& val, int less_than) {
 int new_val;
 int old_val = val.load();
 do
 {
   if (old_val > less_than) return old_val;
   new_val = old_val + 1;
 } while (!val.compare_exchange_weak(old_val, new_val));

 return new_val;
}

如果有人不知道如何工作compare_exchange_weak:
compare_exchange_weak reads val,与old_val比较,如果它们不相等,则将val保存为old_val。如果相等,则将new_val保存到val。

If somebody don't know how works compare_exchange_weak: compare_exchange_weak reads val, compares with old_val, and if they are not equal then saves val to old_val. If it is equal then save new_val to val.

推荐答案

不,没有特别支持增加小于值的值。你的代码与你能得到的一样高效。 C ++ 11中没有等待的变体

No, there is no special support for incrementing values less than a value. Your code is as efficient as you can get. There is no wait-free variant in C++11

有无限数量的可能的增量如果X模式。硬件制造商决定,增量,如果不改变是他们需要支持的唯一的东西。

There is an unlimited number of possible "increment if X" patterns. The hardware manufacturers decided that "increment if not changed" is the only thing they need to support.

理论上,你可以发明一个硬件平台与一个特殊的汇编代码,但C ++ 11不直接定向。

In theory you could invent a hardware platform with a special assembly code for it, but C++11 does not directly target that.

这篇关于是否有检查前提条件的原子增量,原子值是否小于指定值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆