title: synchronizing 10 threads with atomic bool
body: <p>I'm trying to use 10 threads and each one needs to print his number and the printing needs to be synchronized. I'm doing it as homework and I have to use atomic variables to do it (no locks).</p>
  
  <p>Here what I tried so far:</p>
  
  <pre><code>#include &lt;atomic&gt;
  #include &lt;thread&gt;
  #include &lt;iostream&gt;
  #include &lt;vector&gt;
  
  using namespace std;
  atomic&lt;bool&gt; turn = true;
  
  void print(int i);
  
  int main()
  {
    vector&lt;thread&gt; threads;
  
    for (int i = 1; i &lt;= 10; i++)
    {
      threads.push_back(thread(print, i));
    }
  
    for (int i = 0; i &lt; 10; i++)
    {
      threads[i].join();
    }
  
    return 0;
  }
  
  
  void print(int i)
  {
    bool f = true;
    for (int j = 0; j &lt; 100; j++)
    {
      while((turn.compare_exchange_weak(f, false)) == false)
      { }
      cout &lt;&lt; i &lt;&lt; endl;
      turn = turn.exchange(true);
    }
  }
  </code></pre>
  
  <p>output example:</p>
  
  <pre><code>24 
  
  9143 
  541 
  
  2 
  8
  </code></pre>
  
  <p>expected output: </p>
  
  <pre><code>2
  4
  9
  1
  4
  3
  1
  5 
  4
  10
  8
  </code></pre>