Friday, April 4, 2014

“volatile” keyword in C (and Java)

Problem
What is the significance of the keyword “volatile” in C?
Solution

Lets under stand volatile in C

Volatile tells the compiler not to optimize anything that has to do with the volatile variable.There is only one reason to use it: When you interface with hardware.

Volatile informs the compiler that the value of the variable can change from the outside, without any update done by the code.

Declaring a simple volatile variable:
volatile int x;
int violatile x;

Declaring a pointer variable for a volatile memory (only the pointer address is volatile):
volatile int * x;
int violatile * x;

Declaring a volatile pointer variable for a non-volatile memory (only memory contained is volatile):
int * violatile x;

Declaring a volatile variable pointer for a volatile memory (both pointer address and memo- ry contained are volatile):
volatile int * volatile x; 
int volatile * volatile x;

Volatile variables are not optimized, but this can actually be useful Imagine this function:
int opt = 1;
void Fn(void) {
    start:
        if(opt == 1) goto start;
        else break;
}

At first glance, our code appears to loop infinitely The compiler will try to optimize it to:
void Fn(void) {
    start:
        int opt = 1;
        if (true)
        goto start;
}

This becomes an infinite loop. However, an external program might write '0' to the location of variable opt. Volatile variables are also useful when multi-threaded programs have global variables and any thread can modify these shared variables. Of course, we don’t want optimization on them.

Now lets understand volatile in java

Volatile in java

 The volatile modifier tells the JVM that writes to the field should always be synchronously flushed to memory, and that reads of the field should always read from memory. This means that fields marked as volatile can be safely accessed and updated in a multi-thread application without using native or standard library-based synchronization. (This does not apply to long or double fields, which may be non-atomic on some JVMs. However, it always applies to reference-typed fields.) The relevant parts of the JLS are 8.3.1.4, 17.4 and 17.7.


References
http://tianrunhe.wordpress.com/2012/04/12/keyword-violatile-in-c/
http://stackoverflow.com/questions/246127/why-is-volatile-needed-in-c
http://stackoverflow.com/questions/3544919/what-are-transient-and-volatile-modifiers 

Reactions:

0 comments:

Post a Comment