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> </code> | (Thread 2) <code> </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
- Wikipedia (en) About Memory barrier
- Memory visibility and memory barrier (related link)
- Memory visibility and memory barriers
- [Recommended] volatile and memory barriers 1
- LINUX KERNEL MEMORY BARRIERS 2
- [Recommended] Memory Visibility and Memory Barrier
- [Recommended] Sukkarak's Programming Story: C++11 atomic (memory visibility and barriers) 3
- [https://msdn.microsoft.com/en-us/library/windows/desktop/ee418650(v=vs.85.aspx Lockless Programming Considerations for Xbox 360 and Microsoft Windows]
- [Recommended] Barriers - Mun-c Blog 4
- Documentation/memory-barriers.txt (v3.17)
Preshing on Programming
- An Introduction to Lock-Free Programming
- The Synchronizes-With Relation
- Acquire and Release Fences
- Double-Checked Locking is Fixed In C++11