title: C++: Preventing multiple functions from being executed at the same time
body: <p>I ask this questions as all the <strong>mutex</strong> documentations I find deal with a single function and I think my case is very common.</p>
  
  <p>My question is whether the following code won't only prevent <code>func1()</code> or <code>func2()</code> from being executed multiple times in parallel, but whether it would also prevent <code>func1()</code> and <code>func2()</code> from being executing at the same time?</p>
  
  <pre><code>#include &lt;mutex&gt;
  
  std::mutex my_mutex;
  
  void func1() {
      my_mutex.lock();
      // do something ...
      my_mutex.unlock();
  }
  
  void func2() {
      my_mutex.lock();
      // do something ...
      my_mutex.unlock();
  }
  </code></pre>
  
  <p>As I understand many people usually copy code from Stackoverflow, I am adding another version of my sample code, after adding @Al_Bundy's input - using lock_guard, which is destructed when the function ends and thus makes sure your mutex is released when the function ends and the guard is destructed. It is much more safe, as your function could get an exception and your mutex could stay locked when you manually unlock it instead of using lock guard:</p>
  
  <pre><code>#include &lt;mutex&gt;
  
  std::mutex my_mutex;
  
  void func1() {
      std::lock_guard&lt;std::mutex&gt; locker(my_mutex);
      // do something ...
  }
  
  void func2() {
      std::lock_guard&lt;std::mutex&gt; locker(my_mutex);
      // do something ...
  }
  </code></pre>