title: C++ threads add two array to one result array
body: <p>I have n threads with n arrays. For example 2 threads with 2 arrays with some data (people names). </p>
  
  <p>I need to write a program that creates new result array and adds data from these 2 threads</p>
  
  <pre><code>People A[15];
  atomic&lt;int&gt; n;
  mutex n_mutex;
  
  void threadFunc(People data[], int peopleCount, int tid) {
  
      for (int q = 0; q &lt; peopleCount; ++q)
      {
          cout &lt;&lt; "In loop" &lt;&lt; endl;
          lock_guard&lt;mutex&gt; lock(n_mutex);
          A[n.load()].setName(data[q].getName());
          A[n.load()].setArrayId(q);
          A[n.load()].setThreadId(tid);
          n++;
      }
  }
  
  int main() {
  
      threads[0] = thread(threadFunc, people1, allPeopleCount[0], 1);
      threads[1] = thread(threadFunc, people2, allPeopleCount[1], 2);
  
      for (auto&amp; th : threads) {
          th.join();
      }
  
      for (int i = 0; i &lt; 6; i++)
      {
          cout &lt;&lt; "Thread_" &lt;&lt; A[i].getThreadId() &lt;&lt; " " &lt;&lt; A[i].getArrayId() &lt;&lt; " name: " &lt;&lt; A[i].getName() &lt;&lt; endl;
      }
  }
  </code></pre>
  
  <p>And it prints in random order which is fine</p>
  
  <pre><code>Thread_1 0 name: Adam
  Thread_2 0 name: John
  Thread_1 1 name: Robert
  Thread_1 2 name: Greg
  Thread_2 1 name: David
  Thread_2 2 name: Michael
  </code></pre>
  
  <p>However if I delete this line</p>
  
  <pre><code>cout &lt;&lt; "In loop" &lt;&lt; endl;
  </code></pre>
  
  <p>from threadFunc it prints following: </p>
  
  <pre><code>Thread_1 0 name: John
  Thread_1 1 name: Adam
  Thread_1 2 name: Robert
  Thread_2 0 name: David
  Thread_2 1 name: Greg
  Thread_2 2 name: Michael
  </code></pre>
  
  <p>And it looks like it works sequentially. So why does it change to that when i use dont use cout to print data in console? Data is always in order without using it.</p>