22 July 2007

The meaning of "volatile" is: Don't assume that variable won't vary, re-read it every time using it. I thought it was needed only to synchronize accesses of certain variable in mulit-thread processes. But, there are actually more reasons to use "volatile".

To deter potential inappropriate compilation optimization

Some hardware/compiler may never re-read the variable if the value doesn't change according to the context (even it may be altered in another thread). Example from The Java Programming Language(3rd ed.) Section 10.10 (P.260):

currentValue = 5;
for(;;){
    display.showValue(currentValue);
    Thread.sleep(1000);
}

According to above code snippet, the "currentValue" will never change. So the compiler may optimize generated code so that "currentValue" is replaced by "5". But that "optimization" can be an error if the "currentValue" would change in another thread. To avoid such "optimization", we should qualify "currentValue" with "volatile".

When "longjmp" is involved

This is explained in Advanced Programming in the UNIX Environment section 7.10 subsection "Automatic, Register and Volatile Variables". The problem is that some variables may be changed after "setjmp" and before "longjmp". What are those variables' values after "longjmp" back to a previous point? Values of automatic and register variables are indeterminate. But automatic variables qualified by "volatile" are said to be left as it is.

int main(){
    int i = 1;
    volatile int v = 1;

    if (setjmp (jmpBuf) !=0){
        // after longjmp
        // value of i is not determinate
        // while v is 2 (value assigned after setjmp)
        printf ("i = %d, v = %d\n", i, v);
        return 0;
    }

    i = 2; v = 2;

    longjmp (jmpBuf, 1);
}


blog comments powered by Disqus