0

Why does using thread_local variable cause a segfault?

For the above question, I have two new questions.

  1. When I use the non-local thread_local variable, my main thread is not executing the construction.

  2. 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 >>>>
coordinate
  • 99
  • 5
  • 1
    for question 1 see the duplicate and https://en.cppreference.com/w/cpp/language/initialization#Deferred_dynamic_initialization, for question 2 you haven't initialised the elements of `a` so your program's behaviour is undefined – Alan Birtles Apr 11 '22 at 13:43
  • e.g. https://godbolt.org/z/699dYez1q uses `t` in main and initialises `a` so `t` is constructed 3 times and `0` is printed instead of a random value – Alan Birtles Apr 11 '22 at 13:55

0 Answers0