Volatile (computer programming): Difference between revisions

Content deleted Content added
SmackBot (talk | contribs)
m "External links" is plural as there are more than one. Fixed using AWB
Line 1:
In [[computer programming]], a [[variable]] or object declared with the '''volatile''' [[Keyword (computer programming)|keyword]] may be modified externally from the declaring object. For example, a variable that might be concurrently modified by multiple [[Thread_Thread (computer_sciencecomputer science)|threads]] should be declared volatile. Variables declared to be volatile will not be optimized by the [[compiler]] because their value can change at any time. Note that operations on a volatile variable are still ''not'' [[Atomic operation|atomic]].
 
==What can happen if volatile is not used?==
The following piece of [[C_programming_languageC programming language|C]] [[source code]] demonstrates the use of the volatile keyword.
 
<pre><nowiki>
Line 18:
In this example, the code sets the value stored at [[memory address|___location]] 100 in the computer system to 0. It then starts to poll the address until it changes to 255.
An [[Compiler_optimizationCompiler optimization|optimizing]] compiler will assume that no other code will change the value stored in ___location 100 and so it will remain equal to 0. The compiler will then replace the [[program loop|while loop]] with something similar to this: -
 
<pre><nowiki>
Line 52:
With this modification the code will remain as it is and the CPU will detect the change when it occurs.
 
==External linklinks==
*[http://www.programmersheaven.com/articles/pathak/article1.htm Use of volatile at Programmer's Heaven]
*[http://msdn2.microsoft.com/en-us/library/12a04hfd.aspx volatile keyword in Visual C++]