title: Are function-local static mutexes thread-safe?
body: <p>In the following program I attempt the make the <code>print</code> function thread-safe by using a function-local mutex object:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;chrono&gt;
  #include &lt;mutex&gt;
  #include &lt;string&gt;
  #include &lt;thread&gt;
  
  
  void print(const std::string &amp; s)
  {    
      // Thread safe?
      static std::mutex mtx;
      std::unique_lock&lt;std::mutex&gt; lock(mtx);
      std::cout &lt;&lt;s &lt;&lt; std::endl;
  }
  
  
  int main()
  {
      std::thread([&amp;](){ for (int i = 0; i &lt; 10; ++i) print("a" + std::to_string(i)); }).detach();
      std::thread([&amp;](){ for (int i = 0; i &lt; 10; ++i) print("b" + std::to_string(i)); }).detach();
      std::thread([&amp;](){ for (int i = 0; i &lt; 10; ++i) print("c" + std::to_string(i)); }).detach();
      std::thread([&amp;](){ for (int i = 0; i &lt; 10; ++i) print("d" + std::to_string(i)); }).detach();
      std::thread([&amp;](){ for (int i = 0; i &lt; 10; ++i) print("e" + std::to_string(i)); }).detach();
      std::this_thread::sleep_for(std::chrono::milliseconds(100));
  }
  </code></pre>
  
  <p>Is this safe?</p>
  
  <p>My doubts arise from  <a href="https://stackoverflow.com/questions/2955921/thread-safe-initialization-of-function-local-static-const-objects">this question</a>, which presents a similar case.</p>