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/
108
Upvotes
r/cpp • u/david-alvarez-rosa • Mar 24 '26
35
u/Deaod Mar 24 '26
This article misattributes the idea of caching head/tail to Erik Rigtorp. Even in non-academic libraries this was implemented in e.g. https://github.com/cameron314/readerwriterqueue way before 2021.
This was actually published in a paper: P. P. C. Lee, T. Bu and G. Chandranmenon, "A lock-free, cache-efficient multi-core synchronization mechanism for line-rate network traffic monitoring," 2010 IEEE International Symposium on Parallel & Distributed Processing (IPDPS), Atlanta, GA, 2010, pp. 1-12. doi: 10.1109/IPDPS.2010.5470368
This is the earliest article i could find using google, there may be articles ive missed.
20
u/rlbond86 Mar 24 '26
The article does specify this is SPSC, but just to be clear, if multiple threads try to push or pop at the same time, it will be a race condition.
3
u/ReDucTor Game Developer | quiz.cpp-perf.com Mar 24 '26 edited Mar 24 '26
For SPSC the cached head and tail could share the same cache line as the tail and head, so one cache line for consumer and one for producer.Iit would use less memory and for the case of the other thread invalidating it would be no different, the other thread still ends up moving a modified cache line to shared.
Also another improvement is doing index remapping which means subsequent elements dont share the same cache line.
4
u/rzhxd Mar 24 '26
Interesting article, but recently in my codebase I implemented a SPSC ring buffer using mirrored memory mapping (basically, creating a memory-mapped region that refers to the buffer, so that reads and writes are always correct). It would be cool if someone tested performance with this approach instead of manual wrapping to the start of the ring buffer.
3
u/max0x7ba https://github.com/max0x7ba Mar 25 '26
How does it compare with https://max0x7ba.github.io/atomic_queue/html/benchmarks.html
2
u/Rare-Instance7961 Mar 26 '26
In footnote 3, did you mean to say "When head_ is one item behind of tail_, the queue is full."?
2
u/A8XL Mar 31 '26
Nice article! I have implemented a user-friendly Lock-Free Ring Buffer that incorporates all these optimizations:
https://github.com/joz-k/LockFreeSpscQueue
I have also included a built-in performance benchmark against
moodycamel::ReaderWriterQueue.The techniques in your article are powerful, but they are not sufficient to outperform more complex solutions in a synthetic benchmarks like this one using a simple single item push/pop API:
https://max0x7ba.github.io/atomic_queue/html/benchmarks.html
See my performance analysis. My
LockFreeSpscQueueis significantly faster for a larger batch transfers only. However, it is highly scalable.-4
u/nychapo Mar 24 '26
This is nothing new imo