Find the answer to your Linux question:
Results 1 to 2 of 2
Hi all, I know to you what is the exact usage of volatile in a program .I heard that when you declare a variable as volatile it tells the compiler ...
  1. #1
    Just Joined!
    Join Date
    Jun 2007
    Posts
    14

    Regarding question on volatile

    Hi all,
    I know to you what is the exact usage of volatile in a program .I heard that when you declare a variable as volatile it tells the compiler not to do optimization. I want to know exactly in what situations we can use volatile can anyone help me out.

  2. #2
    Just Joined!
    Join Date
    Feb 2007
    Location
    Winnipeg, MB
    Posts
    14

    Volatile

    Volatile is mainly useful in multi-threaded programs. It tells the compiler to immediately assign values to a variable. Say you have this:

    int myVar = 3;

    sleep(3);
    myVar = 6;
    sleep(3);
    myVar = 8;

    The optimizer says, hey, let's skip the busy work and just set myVar to 8. It changes your code to:

    int myVar;
    sleep(3);
    sleep(3);
    myVar = 8;

    But if another thread is running, and waiting to see the variable change to 6, it will never happen and your program won't run as expected.

    You use volatile when two threads are accessing the same variable, but only one of them is changing it. If both threads are changing the variable, volatile is not enough, and you need to use mutexes or some other synchronization mechanism.
    Last edited by myrdos; 06-25-2007 at 10:33 PM. Reason: Fixed syntax

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
...