title: avoid cost of std::mutex when not multi-threading?
body: <p>Suppose I have an application that may or may not have spawned multiple threads.
  Is it worth it to protect operations that need synchronization conditionally with a std::mutex as shown below, or is the lock so cheap that it does not matter when single-threading?</p>
  
  <pre><code>#include &lt;atomic&gt;
  #include &lt;mutex&gt;
  
  std::atomic&lt;bool&gt; more_than_one_thread_active{false};
  
  void operation_requiring_synchronization() {
      //...
  }
  void call_operation_requiring_synchronization() {
      if (more_than_one_thread_active) {
          static std::mutex mutex;
          std::lock_guard&lt;std::mutex&gt; lock(mutex);
          operation_requiring_synchronization();
      } else {
          operation_requiring_synchronization();
      }
  }
  </code></pre>
  
  <p><strong>Edit</strong></p>
  
  <p>Thanks to all who have answered and commented, very interesting discussion.</p>
  
  <p>A couple of clarifications:</p>
  
  <p>The application processes chunks of input, and for each chunk decides if it will be processed in a single-threaded or parallel or otherwise concurrent fashion. It is not unlikely that no multi-threading will be needed.</p>
  
  <p>The <code>operation_requiring_synchronization()</code> will typically consist of a few inserts into global standard containers.</p>
  
  <p>Profiling is, of course, difficult when the application is platform-independent and should perform well under a variety of platforms and compilers (past, present and future).</p>
  
  <p>Based on the discussion so far, I tend to think that the optimization is worth it.</p>
  
  <p>I also think the <code>std::atomic&lt;bool&gt; more_than_one_thread_active</code> should probably be changed to a non-atomic <code>bool multithreading_has_been_initialized</code>. The original idea was to be able to turn the flag off again when all threads other than the main one are dormant but I see how this could be error-prone.</p>
  
  <p>Abstracting the explicit conditional away into a customized lock_guard is a good idea (and facilitates future changes of the design, including simply reverting back to std::lock_guard if the optimization is not deemed worth it).</p>