为什么在不同的编译器或不同平台中的thread_local具有不同的结果?
#include <iostream>
#include <unordered_map>
#include <vector>
#include <thread>
using namespace std;
// not POD
struct A {
std::unordered_map<int, int> m_test;
};
struct B{
thread_local static A a;
};
thread_local A B::a = A();
B b;
void func(){
b.a.m_test[0]++;
}
int main() {
vector<thread> Threads;
for (int i = 0; i < 10; i++) {
Threads.push_back(thread(func));
}
for (int i = 0; i < 10; i++) {
Threads[i].join();
}
return 0;
}
代码片段如上所述。 我在 linux:GCC 4.8.5 和 macOS中构建了相同的代码:Clang13.1.6 ,结果与众不同。在Linux中,出现错误,以17703浮点异常(Core Dovsted)
,但在MacOS中没有发生错误。
我知道thread_local可以在C ++ 11之后在POD类型中使用,但是在这里,我使用unordered_map结构中的unordered_map,内部内存在堆中,而不是静态或全局存储区域。因此,我想知道这是否是因为不同的编译器如何实现C ++标准? 如何在Linux平台上解决此运行时错误?
#include <iostream>
#include <unordered_map>
#include <vector>
#include <thread>
using namespace std;
// not POD
struct A {
std::unordered_map<int, int> m_test;
};
struct B{
thread_local static A a;
};
thread_local A B::a = A();
B b;
void func(){
b.a.m_test[0]++;
}
int main() {
vector<thread> Threads;
for (int i = 0; i < 10; i++) {
Threads.push_back(thread(func));
}
for (int i = 0; i < 10; i++) {
Threads[i].join();
}
return 0;
}
the code snippet is showed as above.
I built the same code in Linux: gcc 4.8.5 and MacOS:clang13.1.6 , outcome is the different . In Linux, An error occurred as 17703 Floating point exception(core dumped)
, but in MacOS there was no error occurred.
I know thread_local can use in POD type after c++11, but here I use the unordered_map in struct, which internal memory is in the heap, not in the static or global storage area. So I wonder if this is because of how different compilers implement the C++ standard?
And how can I solve this runtime error on the linux platform?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
基于对编译器资源管理器的测试,这似乎是2019年为9+,8.4+和7.5+版本修复的GCC错误。该代码应按照发布的方式工作正常。没有错。
可能是此错误。
我建议您安装并使用GCC的最新版本。
Based on testing on compiler explorer, this seems to be a GCC bug fixed in 2019 for versions 9+, 8.4+ and 7.5+. The code should work fine as posted. There is nothing wrong with it.
Probably it is this bug.
I recommend you install and use a more up-to-date version of GCC.