The trouble with volatile
Posted May 15, 2007 11:12 UTC (Tue) by
IkeTo (subscriber, #2122)
In reply to:
The trouble with volatile by giraffedata
Parent article:
The trouble with volatile
> it says the value may change all by itself.
I think the inaccuracy and uselessness of this statement is what Linus is really objecting to. With this being inaccurate and useless, the compiler are forced to do useless things as a result. But those are side effects, the real culprit is still the inaccuracy and uselessness.
I believe the inaccuracy of "volatile" is that it says the memory is always changing, which is not really the case. The memory is changed by some other threads, or by some reordering done by some smart CPUs. It is definitely not "changing all the time", with the exception of I/O mapped memory which might.
I think it is mostly useless, because in most cases a simple "volatile" will not do what is intended, and to do what is intended you need something that will make volatile redundant.
E.g., if you are afraid of some other threads changing your variables, you need a lock to prevent that, rather than just an advice to the compiler not to optimize things out; and once you get that, the CPU reordering is dealt with, and the variable is no longer changing at all within the critical region, so you don't want volatile.
Another reply supplies another example: if you do inter-processor communications, "volatile" is not sufficient, because the instruction reordering done by the CPU causes the result to be erratic. You need something like barrier(), rmb(), wmb(), etc. Once you have that, "volatile" is redundant. Yes, those operations are over-general, but at least they work.
What if you really want to do I/O memory mapped read/write? Again, you need memory barriers for the code to work correctly, and once you have them, you don't need volatile.
> Then Linus misinterprets the English word "volatile" and claims that data
> isn't volatile; rather accesses are volatile. The opposite is true.
I agree that it is difficult to characterize an "access" is "volatile" or not, and I admit that I don't quite understand the statement. On the other hand, while "data is volatile" might be true for some time during the execution of the kernel, the "volatile" in the C language does not provide you the abstraction that you need most of the time.
(
Log in to post comments)