title: Initialize C runtime by multiple threads?
body: <p>I am using MinGW-w64 on Windows. I am trying to make sense what is happening inside the CRT startup functions. The program entry point is <code>mainCRTStartup()</code>. This function initializes buffer security cookie, and then jumps to <code>__tmainCRTStartup()</code>, which ultimately calls <code>main()</code>. Now inside the <a href="https://sourceforge.net/p/mingw-w64/mingw-w64/ci/master/tree/mingw-w64-crt/crt/crtexe.c" rel="nofollow noreferrer">source code</a> of <code>__tmainCRTStartup()</code> there is a curious operation:</p>
  
  <pre><code>while((lock_free = InterlockedCompareExchangePointer ((volatile PVOID *) &amp;__native_startup_lock, fiberid, 0)) != 0)
  {
    if (lock_free == fiberid)
    {
      nested = TRUE;
      break;
    }
    Sleep(1000);
  }
  </code></pre>
  
  <p>Here <code>fiberid</code> is set to the base address of the thread stack.</p>
  
  <p>It seems that the code is preventing multiple threads or fibers initializing CRT simultaneously. But why would there be multiple threads running <code>__tmainCRTStartup()</code> ? Since all threads share the same address space, wouldn't it be sufficient to just initialize CRT once? Also difficult to understand is the if-block inside the loop. To trigger this condition the <code>__native_startup_lock</code> must be already set to <code>fiberid</code>, which implies that the thread in question has already exited the loop. I do not see what kind of feature MinGW is trying to support here.</p>
  
  <p><strong>Update</strong>:</p>
  
  <p>OK. I found a copy of Visual Studio 2013, shipped with the annotated CRT source code. Here's the annotation:</p>
  
  <pre><code>/*
   * There is a possiblity that the module where this object is
   * linked into is a mixed module. In all the cases we gurantee that
   * native initialization will occur before managed initialization.
   * Also in anycase this code should never be called when some other
   * code is initializing native code, that's why we exit in that case.
   */
  </code></pre>
  
  <p>This may explain the <code>nested</code> condition in the loop, but still I do not see why multithreading is involved here.</p>