title: Fill an array from different threads concurrently c++
body: <p>First of all, I think it is important to say that I am new to multithreading and know very little about it. I was trying to write some programs in C++ using threads and ran into a problem (question) that I will try to explain to you now:</p>
  
  <p>I wanted to use several threads to fill an array, here is my code: </p>
  
  <pre><code>static const int num_threads = 5;
  int A[50], n;
  
  //------------------------------------------------------------
  void ThreadFunc(int tid)
  {
      for (int q = 0; q &lt; 5; q++)
      {
          A[n] = tid;
          n++;
      }
  }
  
  //------------------------------------------------------------
  int main()
  {
          thread t[num_threads];
          n = 0;
          for (int i = 0; i &lt; num_threads; i++)
          {
              t[i] = thread(ThreadFunc, i);
          }
  
          for (int i = 0; i &lt; num_threads; i++)
          {
              t[i].join();
          }
          for (int i = 0; i &lt; n; i++)
              cout &lt;&lt; A[i] &lt;&lt; endl;
  
      return 0;
  }
  </code></pre>
  
  <p>As a result of this program I get:
  0
  0
  0
  0
  0
  1
  1
  1
  1
  1
  2
  2
  2
  2
  2
  and so on.</p>
  
  <p>As I understand, the second thread starts writing elements to an array only when the first thread finishes writing all elements to an array. 
  The question is why threads dont't work concurrently? I mean why don't I get something like that:</p>
  
  <p>0
  1
  2
  0
  3
  1
  4
  and so on. </p>
  
  <p>Is there any way to solve this problem?</p>
  
  <p>Thank you in advance.</p>