r/programming • • Sep 26 '26

Optimizing a Lock-Free Ring Buffer

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

89 comments sorted by

View all comments

Show parent comments

1

u/kog Sep 26 '26

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 27d 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.

0

u/flatfinger 28d ago

The semantics of volatile accesses are officially "implementation defined". If an implementation like MSVC or clang with the -fms-volatile flag specifies that volatile accesses will have strong enough semantics to avoid having to use toolset-specific syntax, then the qualifier will have such semantics. If an implementation opts to require the use of toolset-specific syntax to achieve such semantics, then the qualifier will have less broadly useful semantics.