gpt4 book ai didi

c++ - 为什么这个计算在 boost::thread 和 std::thread 中给出不同的结果?

转载 作者:IT老高 更新时间:2023-10-28 22:39:08 26 4
gpt4 key购买 nike

当这个浮点计算在boost::thread中执行时,它给出的结果与在std::thread或主线程中执行时不同。

void print_number()
{
double a = 5.66;
double b = 0.0000001;
double c = 500.4444;
double d = 0.13423;
double v = std::sin(d) * std::exp(0.4 * a + b) / std::pow(c, 2.3);

printf("%llX\n%0.25f\n", *reinterpret_cast<unsigned long long*>(&v), v);
}

这似乎是因为 boost::thread 默认使用 53 位内部精度进行 float 学运算,而主线程使用 64 位精度。如果在创建 boost::thread 后使用 _fpreset() 重置 FPU 单元的状态,结果与主线程中的结果相同。

我正在使用 Embarcadero C++ Builder 10.1(编译器 bcc32c 版本 3.3.1)和 Boost 1.55.0。我的环境是 Windows 7,我正在为 32 位 Windows 目标构建。

工作示例:

#include <tchar.h>
#include <thread>
#include <boost/thread.hpp>
#include <cstdio>
#include <cmath>
#include <cfloat>

namespace boost { void tss_cleanup_implemented() {} }

void print_number()
{
double a = 5.66;
double b = 0.0000001;
double c = 500.4444;
double d = 0.13423;
double v = std::sin(d) * std::exp(0.4 * a + b) / std::pow(c, 2.3);

// Edit:
// Avoiding the undefined behaviour by a reinterpret_cast, as
// mentioned in some answers and comments.
unsigned long long x;
memcpy(&x, &v, sizeof(x));

printf("%llX\n%0.25f\n", x, v);
}

void print_number_2()
{
// Reset FPU precision to default
_fpreset();
print_number();
}

int _tmain(int argc, _TCHAR* argv[])
{
print_number();

std::thread t1(&print_number);
t1.join();

boost::thread t2(&print_number);
t2.join();

boost::thread t3(&print_number_2);
t3.join();

getchar();
return 0;
}

输出:

3EAABB3194A6E99A
0.0000007966525939409087744
3EAABB3194A6E99A
0.0000007966525939409087744
3EAABB3194A6E999
0.0000007966525939409087488
3EAABB3194A6E99A
0.0000007966525939409087744

问题:

  • 为什么会这样?新线程不应该从父线程继承浮点环境吗?
  • 这是编译器或 Boost 中的错误,还是我的预期错误?

最佳答案

这个:*reinterpret_cast<unsigned long long*>(&v)未定义的行为为 v不是 unsigned_long_long .如果要复制 double 的二进制表示为整数类型,使用 memcpy() .请注意,即使使用 memcpy() ,它的实现定义了二进制表示的样子,但你可以保证你可以“加载你保存的内容”。没有更多的AFAIK。

关于c++ - 为什么这个计算在 boost::thread 和 std::thread 中给出不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38371567/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com