4.1.4 Memory Barriers

Memory barriers will be considered in more detail in Section [*] and Appendix [*]. In the meantime, consider the following simple lock-based critical section:



  1 spin_lock(&mylock);
  2 a = a + 1;
  3 spin_unlock(&mylock);


Figure: CPU Meets a Memory Barrier
\resizebox{3in}{!}{\includegraphics{cartoons/barrier}}

If the CPU were not constrained to execute these statements in the order shown, the effect would be that the variable ``a'' would be incremented without the protection of ``mylock'', which would certainly defeat the purpose of acquiring it. To prevent such destructive reordering, locking primitives contain either explicit or implicit memory barriers. Because the whole purpose of these memory barriers is to prevent reorderings that the CPU would otherwise undertake in order to increase performance, memory barriers almost always reduce performance, as depicted in Figure [*].



Paul E. McKenney 2011-12-16