Search This Blog

Saturday, April 19, 2014

Volatile keyword in C

Volatile is a type qualifier. It stop compiler to optimize certain area of code and prevent compiler to assume value of a variable hasn't changed. so compiler leave that segment code without optimized.
     here is one example from #http://en.wikipedia.org/wiki/Volatile_variable

Without Volatile

Before compilation

static int foo;
 
void bar(void) {
    foo = 0;
 
    while (foo != 255)
         ;
}

Optimizing compiler observer that there is no other possible to change the value stored in foo. so compiler take the default value 0 and optimize the loop in to infinite .
After compilation
void bar_optimized(void) {
    foo = 0;
 
    while (true)
         ;
}

With Volatile
static volatile int foo;
 
void bar (void) {
    foo = 0;
 
    while (foo != 255)
        ;
}

Here compiler will not assume any value and it will let the foo variable for the system to change the value.

Volatile is a type qualifier not a storage class so it does not change the area of storage

In kernel
Volatile is used in optimization barrier primitives. In Linux barrier() macro is used, which acts as an optimization barrier. barrier() macro defined as-
 
/* Optimization barrier */
/* The "volatile" is due to gcc bugs */
#define barrier() __asm__ __volatile__("": : :"memory")

The volatile keyword disallow the compiler to reshuffle the asm instruction with the other instructions of the program.
Above example is taken from one of the kernel synchronization so called memory barrier.

Volatile keyword also allow access to memory mapped devices, allow usage of variable between set jump and long jump

1 comment:

  1. please provide some more info regarding volatile with some examples

    ReplyDelete