title: Multithreading and OOO execution.
body: <pre><code>int main() {
      int  f = 0, x=0;
  
      std::thread *t  = new std::thread([&amp;f, &amp;x](){ while( f == 0); std::cout &lt;&lt; x &lt;&lt; endl;});
      std::thread *t2 = new std::thread([&amp;f, &amp;x](){ x = 42; f = 1;});
  
      t-&gt;join();
      t2-&gt;join();
      return 0;
  
  }
  </code></pre>
  
  <p>From what I know, theoritically it is possible to get stdout equals to <code>0</code> against to our intuition ( we are expecting <code>42</code> as a result. But, CPU can execute out of order instructions and in fact, it is possbile to execute program in that order:</p>
  
  <p>( We assume that we have > 1 cores in our CPU)</p>
  
  <p>So, <code>thread#2</code> on the second core executed first ( because of the OOO meachanism) <code>f = 1</code>  and then, <code>thread#1</code> on the first core executed first program: <code>while( f == 0); std::cout &lt;&lt; x &lt;&lt; endl</code>. So, the output is <code>0</code>.</p>
  
  <p>I tried to get such output but I always get <code>42</code>. I ran that program 1000000 times and the result was always same = <code>42</code>. </p>
  
  <p>(I know that it is not secure, there is data race).</p>
  
  <p>My questions are:</p>
  
  <ol>
  <li>Am I right or I am wrong? Why?</li>
  <li>If I am right, is it possible to force to get output equals to <code>0</code>?</li>
  <li>How to make safe this code? I know about mutex/semaphores and I could protect <code>f</code> with mutex but I have heard something about memory fences, please say me more. </li>
  </ol>