添加原子<double>和双精度
Add atomic<double> and double
我想添加两个值:
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;
}
相关文章:
- 如何防止 c++ 在从浮点型转换为双精度型(不适用于 IO)时添加额外的小数?
- 正在将csv文件读取为双精度矢量
- 我可以信任表示整数的浮点或双精度来保持精度吗
- 如何在C++中的同一函数中使用字符串和双精度
- 特征::矩阵<双精度,1,3> 结构类型函数中的返回类型函数
- 检查是否以特定精度给出双精度
- 转换函数,将 std::数组的双精度作为参数或双精度作为参数单独转换
- C 字符串返回字符串的整数/双精度/长整型值
- 为什么将双精度转换为 int 似乎在第 16 位数字之后将其四舍五入?
- 如何使双精度值的 C++ 和 C# 中的结果相同
- 使用浮点数和双精度数的非常小数字的数学
- 使用 Xcode 将双精度存储在数组C++中
- 在 C++ 中将双精度变量写入二进制文件
- 如何从字符串转换为双精度*
- 为什么我的数组双精度函数不起作用?
- 高精度双精度的 Sprintf 格式化问题
- C++ cout 将双精度对齐到精度 2 并正确对齐
- 将指针数组分配给双精度
- C++如何将字符串逐行转换为双精度
- 长双精度C++是IEEE二进制128的实现吗?