title: Initialization of thread-local variables
body: <p>I was recently using an object whose purpose is to allocate and deallocate memory as a singleton. Something like</p>
  
  <pre><code>class MyValue
  {
    // ...
  
    static Allocator&amp; GetAllocator()
    {
      static Allocator allocator;
      return allocator;
    }
  
    // ...
  };
  </code></pre>
  
  <p>I realized later <code>Allocator</code> is not thread-safe: when multiple threads were using the same allocator concurrently, occasionally strange things were happening, causing assertions and segmentation faults.</p>
  
  <p>Solution: use different allocators for different threads:</p>
  
  <pre><code>class MyValue
  {
    // ...
  
    static Allocator&amp; GetAllocator()
    {
      thread_local static Allocator allocator;
      return allocator;
    }
  
    // ...
  };
  </code></pre>
  
  <p>Awesome! My problems are gone! Just one question:
  <strong>Will my allocator variable be initialized every time a thread is created, even if the majority of threads won't use this variable?</strong></p>
  
  <p>The initialization of the allocator might be heavy operation, so I would like it to be initialized only when it is actually required, not in every thread.</p>
  
  <p>I read that <code>thread_local</code> variables are <em>allocated</em> by each thread. Does that mean they are also <em>constructed</em>? And does this allocation (or construction) happen systematically for each thread that is created or just for threads that use it?</p>
  
  <p>I faintly remember hearing in a course that most details about threads and thread-local storage are platform dependent. If this is the case, I'm particularly interested in Linux and FreeBSD.</p>
  
  <hr>
  
  <p>Related (interesting reads, but I could not find the answer there):</p>
  
  <ul>
  <li><p><a href="https://stackoverflow.com/questions/47498215/destruction-of-thread-local-objects">Destruction of thread_local objects</a></p></li>
  <li><p><a href="https://stackoverflow.com/questions/11983875/what-does-the-thread-local-mean-in-c11">What does the thread_local mean in C++11?</a></p></li>
  <li><p><a href="https://stackoverflow.com/questions/13106049/what-is-the-performance-penalty-of-c11-thread-local-variables-in-gcc-4-8">What is the performance penalty of C++11 thread_local variables in GCC 4.8?</a></p></li>
  </ul>