The trouble with volatile
Posted May 12, 2007 3:46 UTC (Sat) by
mikov (subscriber, #33179)
Parent article:
The trouble with volatile
There have been some very fun discussions about volatile on comp.std.c in the past. Basically my opinion, although I have never been able to convince anybody, is that volatile is _always_ wrong even in user mode. Period. It serves no purpose whatsoever that couldn't be achieved much better and more reliably in a different way. To put it another way, volatile is useless in a 100% standard-compliant C program, and if the program is not 100% compliant, then it is even more useless.
Also, not all compilers implement it. Notably Borland C in some of its versions didn't.
People might argue that it is useful with signals or longjmp(), but the need for volatile in such scenarios is always an indication of a serious problem in the code.
The way I find it easy to think about it or explain it is that volatile does nothing to prevent the CPU reordering memory accesses, not to mention the visibility of memory accesses across different CPUs. So, it just muddles the issues.
I want to open a big bracket here and mention that volatile in Java an entirely different beast and is much much more useful. According to the Java memory model, volatile actually has very useful guarantees for memory visibility. (Perhaps Linux should consider Java for the kernel :-)
Still, I agree with what already has already been said earlier: it is conceptually wrong to mark data as volatile. Accesses should be marked, bit the data itself. So, Java doesn't get it 100% right either. (But of course it wasn't possible to add lightweight volatile accesses to Java without modifying the language).
(
Log in to post comments)