title: Global static initialization threading
body: <p>I have a collection that I am protecting with a mutex.  After initialization it is only ever read, so I won't need a mutex there.</p>
  
  <p>The collection is initialized and populated in global static initializers.  I know that global static initialization is guaranteed within a single translation unit.  Is there any guarantee that global static initialization will be single threaded?</p>
  
  <hr>
  
  <p>I have a static collection that protected by a Schwarz counter and is populated by constructors of other static objects.  The container is associated with a mutex.  Given that the collection is read-only after <code>main</code> starts, I would like to get rid of the mutex if I can guarantee that static constructors are called in a single thread.</p>
  
  <p>My understanding is that static initialization order is generally well defined within a single translation unit, but unspecified between translation units.  Does the standard allow for the static objects to be initialized/constructed by different runtime provided threads?</p>
  
  <hr>
  
  <p>Schwarz counter:</p>
  
  <p>Header file:</p>
  
  <pre><code>struct Init
  {
     Init();
     ~Init();
  };
  namespace
  {
     Init _init;
  }
  extern std::map&lt;int, std::unique_ptr&lt;...&gt;&gt; &amp;protected;
  </code></pre>
  
  <p>Source file:</p>
  
  <pre><code>namespace
  {
     int init_count;
     std::aligned_storage&lt;sizeof(std::map&lt;int, std::unique_ptr&lt;...&gt;&gt;), alignof(std::map&lt;int, std::unique_ptr&lt;...&gt;&gt;&gt;)&gt; protected_storage;
  }
  std::map&lt;int, std::uniqe_ptr&lt;...&gt;&gt; &amp;protected = *reinterpret_cast&lt;std::map&lt;int, std::unique_ptr&lt;...&gt;&gt; *&gt;(&amp;protected_storage);
  Init::Init()
  {
     if (!init_counter++)
     {
        new(&amp;protected_storage) std::map&lt;int, std::unique_ptr&lt;...&gt;&gt;();
     }
  }
  Init::~Init()
  {
     if (!--init_counter)
     {
        protected.~std::map&lt;int, std::unique_ptr&lt;...&gt;&gt;();
     }
  }
  </code></pre>
  
  <hr>
  
  <p>Collection population:</p>
  
  <pre><code>struct helper
  {
     helper(...)
     {
        protected.insert(std::make_pair(...));
     }
  };
  </code></pre>
  
  <p>A macro is expanded that creates static instances of helper.</p>