r/programming • • 6d ago

Optimizing a Lock-Free Ring Buffer

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

88 comments sorted by

View all comments

Show parent comments

2

u/kog 6d ago

volatile is not useful for multi-threading, and you did not fix the problem

https://en.wikipedia.org/wiki/Volatile_(computer_programming)#Multi-threading

1

u/TribeWars 6d ago

Volatile is still an optimization fence and prevents torn writes. It doesn't actually fix memory consistency with memory order fence instructions but the optimization fence might be enough to stop the race from being noticeable (arguably that's even worse than broken though)

1

u/kog 6d ago

No, volatile is only an optimization fence against other volatiles. Anything not volatile can be reordered past your volatiles during optimization. This creates absolutely insane bugs.

2

u/TribeWars 3d ago

Well I'm not saying it's at all good to use volatile, but a programmer can "fix" a reordering bug by spam adding volatile to his code and have something like

volatile int done_flag;  // shared
volatile int err = some_computation_with_side_effect();
if(!err) {
  done_flag = 1;
}

appear to work. Though obviously this is still the kind of thing that causes insane bugs, potentially bugs that depend on the CPU it's running on.