3 ms·
C's volatile guarantees very little. It's mostly there for compilers to implement in whatever way is useful for the environment they run in, and so there isn't
by mikeash 9y ago
C's volatile guarantees very little. It's mostly there for compilers to implement in whatever way is useful for the environment they run in, and so there isn't much portable code you can usefully write using volatile.
All it really guarantees is that reads and writes won't be elided. For example:
*x = 42;
*x = 43;
If x is a normal pointer, the compiler can eliminate the first line. If it's a pointer to volatile, the compiler must write both values.
Volatile predates multithreading in C (it was meant for memory-mapped IO and similar things) and hasn't been updated for it, so it has pretty much no useful properties for multithreading. There are no guarantees about reordering when it comes to multiple threads. You're guaranteed to see reads and writes in the correct order from the perspective of the thread your code is running on, but the compiler won't insert any memory barriers, so it's completely up for grabs how other threads might see it.
(More completely, it depends entirely on your CPU's memory model. If you're on an architecture which does strict ordering at the hardware level then you could potentially take advantage of that. If you aren't then you'll see whatever crazy results hardware reordering might produce.)
In contrast, Java's volatile is only about multi-threading. So really, the only thing that's similar between the two languages' use of volatile is how they spell the keyword.