Skip to content
Search

Memory barrier

lastmod 2018-08-17created 2015-04-0610 edits

A memory barrier is a feature that forces the central processing unit or the compiler to enforce the order of certain operations.

A central processing unit can reorder operations through out-of-order execution as long as the results are not affected, and compilers perform similar optimizations. However, when several threads run concurrently, the execution order of the code may change, and another thread may access the memory involved in that part during execution, producing wrong results. Therefore, a memory barrier must be placed to enforce the execution order for specific parts.

Memory visibility

Memory visibility is whether a memory value changed by one Thread can be read correctly by another Thread.

Example

Without a memory barrier, the following code behaves in unintended ways:

(Thread 1) <code>

while(x==0) { }
print y;

</code>

(Thread 2) <code>

y = 10;
x = 1;

</code>

Here, for print y; in Thread 1 to print 10 as intended, the x==0 condition above it must be passed first. However, since y = 10; and x = 1; in Thread 2 have no dependency on each other, the compiler or CPU may swap the order of these two operations. Likewise, in Thread 1, reading the value of y in print y; may happen before reading the value of x in while(x==0).

Android SMP (Symmetric Multiprocessor)

A course on C, C++, and Java programming for symmetric multiprocessor systems:

  • Android SMP(1) - Memory consistency models: Kandroid.org_-_android_smp_01.pdf
  • Android SMP(2) - Data memory barriers: Kandroid.org_-_android_smp_02.pdf
  • Android SMP(3) - Atomic operations: Kandroid.org_-_android_smp_03.pdf
  • Android SMP(4) - Cases, what not to do in C: Kandroid.org_-_android_smp_04.pdf
  • Android SMP(5) - Cases, what not to do in Java: Kandroid.org_-_android_smp_05.pdf
  • Android SMP(6) - Cases, what to do: Kandroid.org_-_android_smp_06.pdf
  • Android SMP(7) - Appendix: Kandroid.org_-_android_smp_07.pdf

See also

Favorite site

Preshing on Programming

References


  1. Volatile_and_memory_barrier.pdf ↩

  2. Kernel.org-doc-memory-barriers.txt.zip ↩

  3. Egloos_zum_com-sweeper-c++11_std_atomic.pdf ↩

  4. Jake.dothome.co.kr_-_Barriers.pdf ↩

  5. Linux_-doc-ko-_memory-barriers.txt.zip ↩