News for hackers. Stuff that matters.
Re:Nine ways to break your systems code using volatile by comex on Friday October 06, 2023 @02:40AM (#37787803)
> Atomics and volatile solve different problems, though.

Yep, that's why atomics are only an alternative to uses of volatile _for atomicity_. For the original use case of accessing hardware registers, volatile is still the correct choice.

It is indeed possible for C11 atomics to be optimized, although interestingly, the three major compilers do very little such optimization. This paper [1] lists some optimizations that are implemented in LLVM and some that aren't; it's from 2015 but from some quick testing it seems like not much has changed since.

[1] https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n44...

Re:Nine ways to break your systems code using volatile by binarycoffee on Friday October 06, 2023 @05:25AM (#37788663)
I have always wondered about that.

If optimizing repeated atomic loads is indeed allowed, waiting for a signal by spinning on an atomic load could loop forever. Yet I have the feeling most people consider such code to be valid. Are they wrong?

Re:Nine ways to break your systems code using volatile by manwe150 on Friday October 06, 2023 @05:49AM (#37788777)
Acquire loads (and stronger) are required not to loop forever, if they could be observable from another thread. It is mentioned in the linked paper.
Re:Nine ways to break your systems code using volatile by gpderetta on Friday October 06, 2023 @08:00AM (#37789552)
Some optimizations are allowed within the rules of the memory model. For example, for an atomic x:

   x=1
   x=2
Can be changed to just x=2. Still forward progress and eventual visibility must be guaranteed.