Class 15: Memory barriers¶
Date: 09.06.2026
Summary¶
Memory barriers are only required where there's a possibility of interaction between two CPUs or between a CPU and a device. If it can be guaranteed that there won't be any such interaction in any particular piece of code, then memory barriers are unnecessary in that piece of code.
[!] Memory barriers are _not_ needed within a given CPU, as CPUs always see their own loads and stores as if they had happened in program order.
TL;DR: Use locks and iowrite. You may want to try atomics in some cases. Be very careful with memory barriers, they are usually not necessary if you use locks and I/O helpers.
Hands-on¶
Analyze examples from "EXAMPLES OF MEMORY BARRIER SEQUENCES" section of Linux kernel memory barriers
Read Circular Buffers
Analyze the example producer/consumer code. How could it break if you remove one, or all of the barriers?
References¶
Extended Asm - Assembler Instructions with C Expression Operands
Preshing on Programming - Memory Reordering Caught in the Act
Lars Wrenger, Dominik Töllner, Daniel Lohmann, Analyzing the memory ordering models of the Apple M1, Journal of Systems Architecture
Owens, S., Sarkar, S., Sewell, P. (2009). A Better x86 Memory Model: x86-TSO