Volatile (computer programming): Difference between revisions

Content deleted Content added
Volatile is not a threading primitive
Line 11:
foo = 0;
while (foo != 255)
continue ;
}
</code>
Line 22:
{
foo = 0;
while (TRUEtrue)
continue;
}
</code>
 
However, <code>foo</code> might represent a ___location that can be changed by other elements of the computer system. For example, the variable may be modified by another [[thread (computer science)|thread]] or [[process (computing)|process]] via [[shared memory]]. It could even be a [[hardware register]] of a device connected to the [[CPU]]. The value stored there could change at any time. The above code would never detect such a change; without the <code>volatile</code> keyword, the compiler assumes the current program is the only part of the system that could cause the value to change. (This is by far the most common situation.)
 
To prevent the compiler from modifying code in this way, the <code>volatile</code> keyword is used in the following manner:
Line 38:
foo = 0;
while (foo != 255)
continue ;
}
</code>
Line 45:
 
For an example of the use of <code>volatile</code> in context, see [[Busy waiting]].
 
 
Note that using volatile as a threading primitive is not guaranteed to work in C, C++, or Java versions 1 to 1.4. There are many systems where it will not. In C, and consequently C++, volatile was intended to allow access to memory mapped devices. Volatile was not intended, and it not implemented on all systems, to be a correct or useful synchronization primitive.
 
==External links==