title: C++ Deadlock example
body: <p>I'm trying to achieve simple deadlock in C++.</p>
  
  <pre><code>std::mutex m1;
  std::mutex m2;
  
  auto f1 = [&amp;m1, &amp;m2]() {
      std::lock_guard&lt;std::mutex&gt; lg1(m1);
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
      std::lock_guard&lt;std::mutex&gt; lg2(m2);
      std::cout &lt;&lt; "A";
  };
  
  auto f2 = [&amp;m1, &amp;m2]() {
      std::lock_guard&lt;std::mutex&gt; lg1(m2);
      std::this_thread::sleep_for(std::chrono::milliseconds(10));
      std::lock_guard&lt;std::mutex&gt; lg2(m1);
      std::cout &lt;&lt; "B";
  };
  
  std::thread thread([&amp;f1, &amp;f2]() {
      for (int i = 0; i &lt; 100; ++i)
      {
          if (i % 2 == 0)
          {
              f1();
          }
          else
          {
              f2();
          }
      }
  });
  
  thread.join();
  </code></pre>
  
  <p>If I understand correctly, I enter f1 function, lock mutex1 and wait 10 ms. In the meantime, f2 lock mutex2. Now, functions will try to lock reverse mutexes, but they are already locked. Why my program is not getting hang and it's print ABAB... and finish?</p>