title: Two threads sharing variable C++
body: <p>So I have two threads where they share the same variable, 'counter'. I want to synchronize my threads by only continuing execution once both threads have reached that point. Unfortunately I enter a deadlock state as my thread isn't changing it's checking variable. The way I have it is:</p>
  
  <pre><code>volatile int counter = 0;
  
      Thread() {
  
               - some calculations - 
  
              counter++;
              while(counter != 2) {
                 std::this_thread::yield();
              }
              counter = 0;
  
              - rest of the calculations -
      }
  </code></pre>
  
  <p>The idea is that since I have 2 threads, once they reach that point - at different times - they will increment the counter. If the counter isn't equal to 2, then the thread that reached there first will have to wait until the other has incremented the counter so that they are synced up. Does anyone know where the issue lies here?</p>
  
  <p>To add more information about the problem, I have two threads which perform half of the operations on an array. Once they are done, I want to make sure that they both have completed finish their calculations. Once they are, I can signal the printer thread to wake up and perform it's operation of printing and clearing the array. If I do this before both threads have completed, there will be issues. </p>
  
  <p>Pseudo code:</p>
  
  <pre><code>Thread() {
  
      getLock()
      1/2 of the calculations on array
      releaseLock()
  
      wait for both to finish - this is the issue
  
      wake up printer thread
  
  }
  </code></pre>