title: How do memory fences work?
body: <p>I need to understand memory fences in multicore machines. Say I have this code</p>
  
  <h2>Core 1</h2>
  
  <pre><code>mov [_x], 1; mov r1, [_y]    
  </code></pre>
  
  <h2>Core 2</h2>
  
  <pre><code>mov [_y], 1; mov r2, [_x]
  </code></pre>
  
  <p>Now the unexpected results without memory fences would be that both r1 and r2 can be 0 after execution. In my opinion, to counter that problem, we should put memory fence in both codes, as putting it to only one would still not solve the problem. Something like as follows...</p>
  
  <h2>Core 1</h2>
  
  <pre><code>mov [_x], 1; memory_fence; mov r1, [_y]  
  </code></pre>
  
  <h2>Core 2</h2>
  
  <pre><code>mov [_y], 1; memory_fence; mov r2, [_x]
  </code></pre>
  
  <p>Is my understanding correct or am I still missing something? Assume the architecture is x86. Also, can someone tell me how to put memory fences in a C++ code?</p>