添加原子<double>和双精度

Add atomic<double> and double

本文关键字:gt 双精度 double lt 添加      更新时间:2023-10-16

我想添加两个值:

auto size = new std::atomic<double>(0);
double packet_size = 64e3;
*size += packet_size;

但是我有一个错误。

no match for ‘operator+=’ (operand types are ‘std::atomic<double>’ and ‘double’)

我应该如何正确添加这两个数字?

即使您也可以创建atomic<float>atomic<double>,原子运算符也不能用于浮点原子。这是因为没有X86(或ARM)的组装指令用于原子上添加浮点值。

解决方法是使用Compare_exchange操作来增加/更改您的原子变量。

#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;
}