Volatile variable
From Free net encyclopedia
In computer programming, a variable or object declared with the volatile keyword may be modified externally from the declaring object. For example, a variable that might be concurrently modified by multiple threads (without locks or a similar form of mutual exclusion) 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.
What can happen if volatile is not used?
The following piece of C source code demonstrates the use of the volatile keyword.
void foo(void) { int *addr; addr = 100; *addr = 0; while (*addr != 255) ; }
In this example, the code sets the value stored at location 100 in the computer system to 0. It then starts to poll the address until it changes to 255.
An 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 while loop with something similar to this: -
void foo(void) { int *addr; addr = 100; *addr = 0; while (1) /* 1 here means TRUE */ ; }
and the program will loop forever.
However, the address might represent a location that can be changed by other elements of the computer system. For example, it could 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 the change.
To prevent the compiler from modifying code in this way, the volatile keyword is used in the following manner: -
void foo(void) { volatile int *addr; addr = 100; *addr = 0; while (*addr != 255) ; }
With this modification the code will remain as it is and the CPU will detect the change when it occurs.