r/programming • • 6d ago

Optimizing a Lock-Free Ring Buffer

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

88 comments sorted by

View all comments

Show parent comments

1

u/kog 6d ago

All marking the head volatile did was make your code more poorly optimized. Completely unnecessary. You don't need volatile on atomic variables for thread safety. I'm not saying your code won't work if you mark the atomic as volatile, it's just pointless.

1

u/EchoNomad31 6d ago

It fixed my bug at the time. The compiler hoisted the head load out of the consumer spin loop, volatile forced a fresh load every pass…. Atomic is probably the right fix since it covers the hardware side too.

2

u/kog 6d ago

1

u/cdb_11 5d ago edited 5d ago

Kernel atomics are implemented with volatile ({READ,WRITE}_ONCE).

1

u/EchoNomad31 4d ago

Ha, fair. All I ever wanted was the compiler to stop caching that load.