Volatile Variable

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 6

Volatile variable

From Wikipedia, the free encyclopedia This article needs additional citations for verification. Please help improve this article by adding reliable references. Unsourced material may be challenged and removed. (July 2009)

In computer programming, particularly in the C, C++, C#, and Java programming languages, a variable or object declared with the volatile keyword usually has special properties related to optimization and/or threading. Generally speaking, the volatile keyword is intended to prevent the (pseudo)compiler from applying any optimizations on the code that assume values of variables cannot change "on their own." The actual definition and applicability of the volatile keyword is often misconstrued in the context of C; and because C++, C#, and Java mystically "inherit" volatile from C, there is a great deal of difference between the semantics and usefulness of volatile in each of these programming languages.

Contents

1 In C and C++ 2 Example of MMIO In C 3 Optimization comparison in C 4 In Java 5 In Ada 6 References 7 External links

[edit] In C and C++


In C, and consequently C++, the volatile keyword was intended to[1]

allow access to memory mapped devices allow uses of variables between setjmp and longjmp allow uses of sig_atomic_t variables in signal handlers.

Operations on volatile variables are not atomic, nor do they establish a proper happens-before relationship for threading. This is according to the relevant standards (C, C++, POSIX, WIN32), and this is the matter of fact for the vast majority of current implementations. The volatile keyword is basically worthless as a portable threading construct.[2][3][4][5][6]

[edit] Example of MMIO In C


In this example, the code sets the value stored in foo to 0. It then starts to poll that value repeatedly until it changes to 255:
static int foo; void bar(void) { foo = 0; while (foo != 255) ; }

An optimizing compiler will notice that no other code can possibly change the value stored in foo, and will assume that it will remain equal to 0 at all times. The compiler will therefore replace the function body with an infinite loop similar to this:
void bar_optimized(void) { foo = 0; while (true) ; }

However, foo might represent a location that can be changed by other elements of the computer system at any time, such as a hardware register of a device connected to the CPU. The above code would never detect such a change; without the volatile keyword, the compiler assumes that the current program is the only part of the system that could change the value (which is by far the most common situation). To prevent the compiler from optimizing code as above, the volatile keyword is used:
static volatile int foo; void bar (void) { foo = 0; while (foo != 255) ; }

With this modification the loop condition will not be optimized away, and the system will detect the change when it occurs.

[edit] Optimization comparison in C


The following C programs, and accompanying disassemblies, demonstrate how the volatile keyword affects the compiler's output. The compiler in this case was GCC.

Disassembly comparison Without volatile


#include <stdio.h> int main() { int a = 10, b = 100, c = 0, d = 0; printf("%d", a + b); a = b; c = b; d = b; printf("%d", c + d); return 0; } }

With volatile
#include <stdio.h> int main() { volatile int a = 10, b = 100, c = 0, d = 0; printf("%d", a + b); a = b; c = b; d = b; printf("%d", c + d); return 0;

gcc -O3 -S without.c -o without.s


.file "without.c" .section .rodata.str1.1,"aMS",@progbits,1 .LC0: .string "%d" .text .p2align 4,,15 .globl main .type main, @function main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) pushl %ebp movl %esp, %ebp pushl %ecx subl $20, %esp movl $110, 4(%esp) movl $.LC0, (%esp) call printf movl $200, 4(%esp) movl $.LC0, (%esp) call printf addl $20, %esp xorl %eax, %eax popl %ecx popl %ebp leal -4(%ecx), %esp ret .size main, .-main .ident "GCC: (GNU) 4.2.1 20070719 [FreeBSD]"

gcc -S with.c -o with.s


.file "with.c" .section .rodata.str1.1,"aMS",@progbits,1 .LC0: .string "%d" .text .p2align 4,,15 .globl main .type main, @function main: leal 4(%esp), %ecx andl $-16, %esp pushl -4(%ecx) pushl %ebp movl %esp, %ebp pushl %ecx subl $36, %esp movl $10, -8(%ebp) movl $100, -12(%ebp) movl $0, -16(%ebp) movl $0, -20(%ebp) movl -8(%ebp), %edx movl -12(%ebp), %eax movl $.LC0, (%esp) addl %edx, %eax movl %eax, 4(%esp) call printf movl -12(%ebp), %eax movl %eax, -8(%ebp) movl -12(%ebp), %eax movl %eax, -16(%ebp) movl -12(%ebp), %eax movl %eax, -20(%ebp)

movl -16(%ebp), %edx movl -20(%ebp), %eax movl $.LC0, (%esp) addl %edx, %eax movl %eax, 4(%esp) call printf addl $36, %esp xorl %eax, %eax popl %ecx popl %ebp leal -4(%ecx), %esp ret .size main, .-main .ident "GCC: (GNU) 4.2.1 20070719 [FreeBSD]"

[edit] In Java
The Java programming language also has the volatile keyword, but it is used for a somewhat different purpose. When applied to a field, the Java volatile guarantees that:
1. (In all versions of Java) There is a global ordering on the reads and writes to a volatile variable. This implies that every thread accessing a volatile field will read its current value before continuing, instead of (potentially) using a cached value. (However, there is no guarantee about the relative ordering of volatile reads and writes with regular reads and writes, meaning that it's generally not a useful threading construct.) 2. (In Java 5 or later) Volatile reads and writes establish a happens-before relationship, much like acquiring and releasing a mutex.[7]

Using volatile may be faster than a lock, but it will not work in some situations.[citation needed] The range of situations in which volatile is effective was expanded in Java 5; in particular, double-checked locking now works correctly.[8]

[edit] In Ada
In Ada, pragma Volatile is a directive rather than a keyword. "For a volatile object all reads and updates of the object as a whole are performed directly to memory."[9]

[edit] References
1. ^ Publication on C++ standards committee website; http://www.openstd.org/jtc1/sc22/wg21/docs/papers/2006/n2016.html 2. ^ Publication on C++ standards committee website; http://www.openstd.org/jtc1/sc22/wg21/docs/papers/2006/n2016.html 3. ^ Volatile Keyword In Visual C++; http://msdn2.microsoft.com/en-us/library/12a04hfd.aspx 4. ^ Linux Kernel Documentation - Why the "volatile" type class should not be used; http://kernel.org/doc/Documentation/volatile-considered-harmful.txt

5. ^ Volatile: Almost Useless for Multi-Threaded Programming (Intel Software Network); http://softwareblogs.intel.com/2007/11/30/volatile-almost-useless-for-multi-threadedprogramming/ 6. ^ C++ and the Perils of Double-Checked Locking; http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf 7. ^ Section 17.4.4: Synchronization Order "The Java Language Specification, 3rd Edition". Sun Microsystems. 2005. Retrieved 2010-11-22. 8. ^ Neil Coffey. "Double-checked Locking (DCL) and how to fix it". Javamex. Retrieved 2009-09-19. 9. ^ "C.6 Shared Variable Control" "Ada Reference Manual". ISO. 2005. Retrieved 2010-05-04.

[edit] External links

Ada Reference Manual C.6: Shared Variable Control

Categories: C programming language | Variable (computer programming) | Concurrency control


Log in / create account Article Discussion Read Edit View history

Navigation

Main page Contents Featured content Current events Random article Donate to Wikipedia

Interaction Toolbox

Help About Wikipedia Community portal Recent changes Contact Wikipedia

What links here

Related changes Upload file Special pages Permanent link Cite this page

Print/export

Create a book Download as PDF Printable version

Languages

esky Deutsch This page was last modified on 7 September 2011 at 16:50. Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. See Terms of use for details. Wikipedia is a registered trademark of the Wikimedia Foundation, Inc., a non-profit organization. Contact us Privacy policy About Wikipedia Disclaimers Mobile view

You might also like