r/cpp • • Mar 24 '26

Optimizing a Lock-Free Ring Buffer

https://david.alvarezrosa.com/posts/optimizing-a-lock-free-ring-buffer/
105 Upvotes

58 comments sorted by

View all comments

Show parent comment

1

u/max0x7ba https://github.com/max0x7ba Mar 27 '26 edited Mar 28 '26

Does a similar penalty apply to any intel architectures?

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,

  • doing 2 stores into 2× larger ring-buffer and next loading the 2nd store could avoid a cache miss, compared to,
  • doing 1 store and next loading from a "mirrored memory mapping" at a virtual address different from that of the store.

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 mmap with the same MAP_FIXED virtual addr in 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.