title: C++ multithreading stopping threads using concurrent variable
body: <p>Trying to make a simple multithreading example using for loops. I'm trying to make them loop in block like this:</p>
  
  <pre><code>Thread 1 printing 0
  Thread 2 printing 0
  Thread 3 printing 0
  Thread 4 printing 0
  Thread 1 printing 1
  Thread 2 printing 1
  Thread 3 printing 1
  Thread 4 printing 1
  </code></pre>
  
  <p>This means: they all print "1", then they all wait for everyone to have done that, then they all print "2", wait again for everyone, print "3", etc.</p>
  
  <p>So I wrote this code:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;thread&gt;
  #include &lt;string.h&gt;
  
  using namespace std;
  
  bool flags[4] = {true,true,true,true};
  
  bool checkAll(){
      bool res = false;
      for(int i=0;i&lt;4;i++){
          res = res|flags[i];
      }
      return res;
  }
  
  void printer(int id){
      for(int i=0;i&lt;100;i++){
          flags[id] = true;
      cout &lt;&lt; "Thread: " &lt;&lt; id &lt;&lt; " printing " &lt;&lt; i &lt;&lt; endl;
      flags[id] = false;
      while(checkAll()) {}
  }
  }
  
  int main(int argc, char *argv[]){
      thread t1(printer,0);
      thread t2(printer,1);
      thread t3(printer,2);
      thread t4(printer,3);
  
      t4.join();
      t3.join();
      t2.join();
      t1.join();
  
      return 0;
  }
  </code></pre>
  
  <p>But it doesn't work as expected. As far as I know, it does not work due to concurrency problems (several threads reading/writing the same variable).</p>
  
  <p>So, I tried to solve it using condition variables:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;thread&gt;
  #include &lt;string.h&gt;
  #include &lt;mutex&gt;
  #include &lt;condition_variable&gt;
  
  using namespace std;
  
  bool flags[4] = {true,true,true,true};
  mutex m;
  condition_variable g_queuecheck;
  bool done = false;
  
  bool checkAll(){
      bool res = false;
      for(int i=0;i&lt;4;i++){
          res = res|flags[i];
      }
      return res;
  }
  
  void printer(int id){
  unique_lock&lt;mutex&gt; locker(m);
  for(int i=0;i&lt;100;i++){
      flags[id] = true;
      cout &lt;&lt; "Thread: " &lt;&lt; id &lt;&lt; " printing " &lt;&lt; i &lt;&lt; endl;
      flags[id] = false;
      g_queuecheck.wait(locker);
  }
  }
  
  void controller(){
  while(!done){
      if(!checkAll()){
          g_queuecheck.notify_all();
      }
      }
  }
  
  int main(int argc, char *argv[]){
  thread t0(controller);
  thread t1(printer,0);
  thread t2(printer,1);
  thread t3(printer,2);
  thread t4(printer,3);
  
  t4.join();
      t3.join();
      t2.join();
      t1.join();
  
      done = true;
      t0.join();
  
      return 0;
  }
  </code></pre>
  
  <p>But doesn't work either. So, here come my questions: Is there a possible way of doing it simple like in the first code? If not, what am I doing wrong in the second one? Thanks a lot.</p>