Home > Software engineering >  Why thread_local in different compiler or different platform has the different outcome?
Why thread_local in different compiler or different platform has the different outcome?

Time:06-05

#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?

CodePudding user response:

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.

  • Related