I have a thread_local variable, which should initialize a class in every thread, but the constructor isn't called, when the threads are opened. The constructor is only called, when I place the instance somewhere in the the code like in my example:
#include <iostream>
#include <thread>
#include <future>
thread_local int val = 0;
class MyClass {
public:
MyClass() {
std::cout << "ctor" << std::endl;
}
void task() {
std::cout << "Hello" << std::endl;
}
};
thread_local MyClass myClass;
void threadMain() {
std::cout << val << std::endl;
}
int main() {
val = 15;
std::cout << val << std::endl;
myClass;//here is the variable placed
std::thread thread1(threadMain);
thread1.join();
auto a = std::async(std::launch::async, threadMain);
a.wait();
return 0;
}
the output with the g++ compiler is:
15
ctor
0
0
Can somebody please explain, what happens here?