Why does using thread_local variable cause a segfault?
For the above question, I have two new questions.
When I use the non-local thread_local variable, my main thread is not executing the construction.
When I run the program I get two results. The first is normal (non-local static and thread-local variables are zero-initialized, https://en.cppreference.com/w/cpp/language/initialization#Static_initialization), and the value obtained by the second t2 thread is a random value.
#include <chrono>
#include <iostream>
#include <memory>
#include <thread>
#include <vector>
class A {
public:
A() {
std::cout << ">>>> constructor >>>>" << std::endl;
a = new int[10];
}
~A() {
std::cout << ">>>> destructor >>>>" << std::endl;
delete[] a;
}
void set(int x) { a[0] = x; }
int get() const { return a[0]; }
private:
int* a;
};
thread_local std::shared_ptr<A> t(new A);
int main() {
std::thread t1, t2;
{
t1 = std::thread([]() {
t->set(1);
std::cout << t->get() << std::endl;
});
t2 = std::thread([]() { std::cout << t->get() << std::endl; });
}
t1.join();
t2.join();
std::cout << ">>>> main >>>>" << std::endl;
}
Result1:
>>>> constructor >>>>
0
>>>> destructor >>>>
>>>> constructor >>>>
1
>>>> destructor >>>>
>>>> main >>>>
Result2:
>>>> constructor >>>>
1
>>>> destructor >>>>
>>>> constructor >>>>
1543507920
>>>> destructor >>>>
>>>> main >>>>