title: How to initialize big thread local objects?
body: <p>In a large C++ program, many threads come and go. Using a thread-pool can mitigate this problem a little bit, but for the purpose of this question suppose the total number of threads is a large value, however, only a small number of them are ever used to call a function in <code>struct TL</code>. The problem is that <code>struct TL</code> contains a few <code>thread_local</code> variables of <strong>very large types</strong> (ie, their instances take a lot of memory). So we want is to make sure that only threads that use <code>struct TL</code> will construct these objects. Is there any design pattern for this situation? (we do not have control over when a thread is created or destroyed).</p>
  
  <p>An easy solution is shown in the following code:</p>
  
  <pre><code>struct TL {
    void func() {
      if(!flag.used) {
        flag.used = true;
        large_1 = new Large_1();
        large_2 = new Large_2(); }
      // use large_1 and large_2
    }
  private:
    struct init {
     ~init() {
        delete large_1;
        delete large_2; }
      bool used = false; };
  
    static thread_local init flag{};
    static thread_local Large_1* large_1 = nullptr;
    static thread_local Large_2* large_2 = nullptr;
  };
  </code></pre>
  
  <p>It uses a flag to check if fields are initialized <strong>every time</strong> we interact with <code>struct TL</code>. Also, when the thread exists, the destructor of <code>flag</code> deletes <code>large_1</code> and <code>large_2</code>. The problem with this approach is that I have check the flag every time I interact with <code>struct TL</code>. I am looking for something like a design pattern for this problem that does not require me to check the flag every time I use <code>struct TL</code>.</p>