Hacker News new | ask | show | jobs
by tialaramex 34 days ago
You said it was for concurrency. The feature you want for that in C (and most languages suitable for this problem) is atomic memory ordering, not the volatile type qualifier.

Microsoft's platform was x86 only for years, and because Intel's design pays for a lot more memory ordering by default than most, on Microsoft's platforms just "volatile" would kinda work even though it was the wrong thing, so Microsoft explicitly grandfathered this for x86 and x86-64 only, you are guaranteed the Acquire-Release ordering even though you didn't ask for it with your volatile type qualifier.

If you were actually thinking of POSIX signals or something similar then yeah, the POSIX requirements say volatile will work, seems like a bad idea to me, but your compiler and other tools are likely also built for POSIX so they've read the same documentation.

1 comments

We were talking about what these features were for when introduced. At the time there were no atomic instructions because there weren’t multiple concurrent execution paths or modern multi layer caching. At the time volatile on a scalar value would only be for preventing optimizations from the compiler assuming linear non-reentrant flow control. I would generally expect that to primarily be used for interrupt handlers in low level code, but posix signal handlers are similar.

Memory mapped registers are typically represented as pointers to volatile structs which I thing correctly represents that the device backing those addresses does not behave like main memory. Reading to or writing from those addresses needs to preserve the -O0 behavior of C where each pointer dereference must be preserved. I just don’t find anything particularly unclear about this, and I certainly don’t see any reason to make the caller have to be extra explicit about it when the reads and writes are already spelled out in the source code.