r/cpp • u/david-alvarez-rosa • Mar 24 '26
Optimizing a Lock-Free Ring Buffer
https://david.alvarezrosa.com/posts/optimizing-a-lock-free-ring-buffer/
105
Upvotes
r/cpp • u/david-alvarez-rosa • Mar 24 '26
View all comments
Show parent comment
1
u/max0x7ba https://github.com/max0x7ba Mar 27 '26 edited Mar 28 '26
Zen 3 and modern Intel CPUs tag L1 cache lines with the untranslated lower bits of the linear/virtual address. Indexing with virtual address bits (where possible) hides TLB latency.
What's different between modern AMD and Intel CPUs are cache sizes, associativity, latency, prefetchers, and higher-level behaviors (e.g., AMD's L3 is typically non-inclusive (victim cache), unlike Intel's often-inclusive LLC).
So,
Provided that the buffer is mapped at the same virtual address in both writer and reader, which often are different processes with different (randomized by default) memory layouts.
Mapping a buffer into one same L1/L2 cache line from different processes requires calling
mmapwith the sameMAP_FIXEDvirtualaddrin different processes.When the buffer is mapped at different virtual address in writer and reader, that creates duplicate L1/L2 cache line copies indexed by different virtual addresses.
The "mirrored memory mapping" method, aka magic-buffer, is a very neat idea in theory -- mapping the same region of physical page frames twice back-to-back to unwrap a ring-buffer. It just that with modern CPUs it may well degrade performance.