title: Is std::mutex recursive (ie non-reentrant)?
body: <p>Test environment:  Ubuntu 18.04.3 LTS  g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0.</p>
  <p>Can std::mutex be reentrant? Why does the following test code 1 pass?</p>
  <p>code1:</p>
  <pre class="lang-cpp prettyprint-override"><code>#include &lt;iostream&gt;
  #include &lt;mutex&gt;
  
  std::mutex g_mtx4val;
  int g_val = 5;
  
  void test() {
    std::lock_guard&lt;std::mutex&gt; lck(g_mtx4val);
    std::cout &lt;&lt; &quot;g_val=&quot; &lt;&lt; g_val &lt;&lt; std::endl;
    if (g_val &gt; 0) {
      --g_val;
      test();
    }
  }
  
  int main() {
    test();
  
    std::cout &lt;&lt; &quot;done ....&quot; &lt;&lt; std::endl;
    return 0;
  }
  </code></pre>
  <pre class="lang-sh prettyprint-override"><code>peanut@peanut:~/demo$ g++ test.cpp 
  peanut@peanut:~/demo$ ./a.out 
  g_val=5
  g_val=4
  g_val=3
  g_val=2
  g_val=1
  g_val=0
  done ...
  </code></pre>
  <p>code2:</p>
  <pre class="lang-cpp prettyprint-override"><code>// Same code 1
  
  int main() {
    std::thread t1(test);
    t1.join();
  
    std::cout &lt;&lt; &quot;done ....&quot; &lt;&lt; std::endl;
    return 0;
  }
  </code></pre>
  <pre class="lang-sh prettyprint-override"><code>peanut@peanut:~/demo$ g++ test2.cpp -lpthread
  peanut@peanut:~/demo$ ./a.out 
  g_val=5
  ^C
  peanut@peanut:~/demo$ 
  </code></pre>
  <p>code2 has a deadlock.
  Why code1 can pass the test?</p>