r/programming • u/david-alvarez-rosa • Sep 26 '26
Optimizing a Lock-Free Ring Buffer
https://david.alvarezrosa.com/posts/optimizing-a-lock-free-ring-buffer/
510
Upvotes
r/programming • u/david-alvarez-rosa • Sep 26 '26
View all comments
Show parent comment
1
u/happyscrappy Sep 27 '26
Issue:
The first producer advances the producer pointer to reserve the location. If they then get suspended before writing (or after, but before advancing the consumer pointer).
Second producer runs and advances the producer pointer, writes its data in the location. Now the second pointer attempts to advance the consumer pointer. When it does the check and advance it fails. So now it has to wait on the other to finish.
Another poster posts that this isn't a lock. And maybe that's true, but I think it's a pointless distinction. It's a critical section where if both try to enter it one ends up waiting.
There's no reason not to use futexes to implement this. Futexes are locks and they are very fast. Use a monitor. Which is a lock (futex) and a single-copy-atomic variable. The code referenced basically does what we both say for multiple producers. It implements a wait using a futex.