C++ 添加原子<;双倍>;加倍
我想添加两个值:C++ 添加原子<;双倍>;加倍,c++,double,atomic,C++,Double,Atomic,我想添加两个值: auto size = new std::atomic<double>(0); double packet_size = 64e3; *size += packet_size; auto size=new std::atomic(0); 双包_大小=64e3; *大小+=数据包大小; 但我犯了个错误 no match for ‘operator+=’ (operand types are ‘std::atomic<double>’ and ‘doub
auto size = new std::atomic<double>(0);
double packet_size = 64e3;
*size += packet_size;
auto size=new std::atomic(0);
双包_大小=64e3;
*大小+=数据包大小;
但我犯了个错误
no match for ‘operator+=’ (operand types are ‘std::atomic<double>’ and ‘double’)
与“operator+=”不匹配(操作数类型为“std::atomic”和“double”)
如何正确地添加这两个数字?即使您可以创建
原子的
和原子的
,也没有为浮点原子定义原子运算符。这是因为没有x86(或ARM)汇编指令用于自动添加浮点值
解决方法是使用比较交换操作来增加/更改原子变量
#include <atomic>
int main()
{
std::atomic<int> i{};
i += 3;
// Peter Cordes pointed out in a comment below that using
// compare_exchange_weak() may be better suited for most
// uses.
// Then again, the needed strength of the exchange depends
// on your application, and the hardware it's intended to run on.
std::atomic<double> f{};
for (double g = f; !f.compare_exchange_strong(g, g + 1.0);)
;
return 0;
}
#包括
int main()
{
std::原子i{};
i+=3;
//彼得·科尔德斯在下面的评论中指出
//compare_exchange_weak()可能更适合大多数情况
//使用。
//此外,交易所所需的实力取决于
//在您的应用程序上以及打算在其上运行的硬件上。
std::原子f{};
对于(双g=f;!f.compare_exchange_strong(g,g+1.0);)
;
返回0;
}
std::atomic
在C++20之前不会出现。你有支持它的编译器吗?@DeiDei;甚至不抱怨。。。您可能想看看这个答案@user1810087,它使用了操作符+
,因此它隐式地将原子变量
转换为双变量
,将它们相加,并重新分配给原子变量。那不是原子的。新的。。。?为什么?如果您已经在使用循环,请使用compare\u exchange\u-weak
,这样它在像ARM这样的LL/SC ISA上编译起来会更好。否则,这将编译为ARM上的嵌套循环。与大多数RISC一样,ARM没有执行任何原子RMW的指令,除了成对的加载/存储条件外,ALU操作按照您的意愿实现。