为什么在不同的编译器或不同平台中的thread_local具有不同的结果?

发布于 2025-02-04 05:45:43 字数 897 浏览 1 评论 0原文

#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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感悟人生的甜 2025-02-11 05:45:43

基于对编译器资源管理器的测试,这似乎是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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文