title: How memory barrier/fence inhibit instruction reordering carried out by CPU?
body: <p>So far as I know,both compiler and CPU can carry out instruction reordering.
  By 'carried out by CPU',I mean that I do not care about instruction reordering that is done by compiler and reordering that is caused by Store Buffer and CPU cache.
  For reordering caused by the Store Buffer and CPU Cache,which was discussed in <a href="http://www.rdrop.com/users/paulmck/scalability/paper/whymb.2010.06.07c.pdf" rel="nofollow">this</a> paper, I have already understood how memory barrier inhibit such reordering(memory reordering).</p>
  
  <p>What I care is such a reordering:</p>
  
  <p>Source code:</p>
  
  <pre><code>data=1; //statement1
  ready=true;//statement2
  </code></pre>
  
  <p>But, ThreadA run on CPU0 executes the above code in the following order:</p>
  
  <pre><code>ready=true;//statement2
  data=1; //statement1
  </code></pre>
  
  <p>That's to say the CPU reorders the instructions,which causes the actual execution order different from the order specified by source code.
  As we know,if we want to make the order of source code be preserved, we can resort to memory barrier(or fence),as:</p>
  
  <p>New Source code:</p>
  
  <pre><code>data=1; //statement1
  smp_wb();//Insert a write barrier here!
  ready=true;//statement2
  </code></pre>
  
  <p>So here comes my question: how memory barrier inhibit instruction reordering here?</p>