title: std::cout from multiple threads
body: <p>I have an application in which I perform costly calculations in parallel worker threads. For simplicity, I write results to stdout directly from these threads.</p>
  
  <p>This worked fine until I changed a few things in an attempt to make the code run faster. First, I replaced std::endl with "\n" to prevent a flushing after every line. And I added the following lines to the init part of my main program:</p>
  
  <pre><code>    std::cin.tie(nullptr);
      std::ios_base::sync_with_stdio(false);
  </code></pre>
  
  <p>The basic structure of the worker thread code looks like this:</p>
  
  <pre><code>while(true) {
      // get data from job queue, protected by unique_lock on std::mutex
  
      // process the data
  
      // print results
      {
          std::lock_guard&lt;std::mutex&gt; lk(outputMutex_);
          std::cout &lt;&lt; "print many results" &lt;&lt; "\n"; // was originally std::endl
      }
  }
  </code></pre>
  
  <p>Since this "optimization", the output of the workers occasionally "mixes". i.e. the mutex does not serve its intended purpose.</p>
  
  <p>Why is this happening? My understanding is that there is just a single stdout stream buffer, and that the data arrives in the corresponding buffer in sequence, even if the output is not flushed from this buffer before releasing the mutex. But that does not seem to be the case...</p>
  
  <p>(I realize that maybe it would be nicer to have the output generated in a separate thread, but then I'd need to pass back these results using another queue, which did not seem necessary here)</p>
  
  <p><strong>Update</strong>: Maybe my post was not clear enough. I do not care about the sequence of the results. The problem is that (for the example above) instead of this:</p>
  
  <pre><code>print many results
  print many results
  print many results
  </code></pre>
  
  <p>I sometimes get:</p>
  
  <pre><code>print many print many results
  results
  print many results
  </code></pre>
  
  <p>And the outputMutex_ is a static member that is shared by all worker threads.</p>