Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Question about the volatile keyword

Tags:

c++

I know that by the volatile keyword,

volatile int k=7; 

we hint the compiler that the variable can be changed at any time but what about a simple int k=7? Can we change it at any time because it is not constant? What is different?

like image 519
dato datuashvili Avatar asked Jul 16 '10 10:07

dato datuashvili


People also ask

What is the volatile keyword useful for?

Volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem.

What is the purpose of volatile keyword in Java?

The volatile modifier is used to let the JVM know that a thread accessing the variable must always merge its own private copy of the variable with the master copy in the memory. Accessing a volatile variable synchronizes all the cached copied of the variables in the main memory.

How does the keyword volatile affect how a variable?

A volatile keyword is used to modify the value of a variable by different threads. It is also used to make classes thread-safe. It means that multiple threads can use a method and instance of the classes at the same time without any problem. The volatile keyword can be used either with primitive type or objects.

What happens when a variable is marked as volatile?

Volatile variables have the visibility features of synchronized but not the atomicity features. The values of the volatile variable will never be cached and all writes and reads will be done to and from the main memory.


2 Answers

volatile prevents compiler optimizations and tells the compiler that the contents of the variable declared volatile can change at any time (i.e. a hardware device, interrupt, or another thread kicks in and writes into the variable's memory location). This means, caching values in CPU registers is not possible.

volatile int a = foo();
d=a+4;
e=a+4;
f=a+4;

Here, the compiler is forced to read a from memory every time it is used. If there was no volatile, precomputing a+4 would be a valid (and effective) optimization.

volatile int a = 4;
return a+5;

Here, the compiler is not allowed to optimize this to a simple return 9; because the contents of a might change between initialization (line 1) and first use (line 2);

like image 102
Alexander Gessler Avatar answered Oct 03 '22 16:10

Alexander Gessler


It's used in low level programming with interrupts and so on mostly

volatile int count;

void test()
{
   while(count< 100) 
   {
        // do nothing
   }
}

//
// Interrupt function called by the hardware automatically at intervals
//
void interrupt()
{
    count = count + 1;
}

if you don't declare the variable as volatile the compiler will probably notice that count can't change in the while loop and so won't bother to actually read the value every time from memory so it will never exit the loop.

If you declare it volatile then the compiler will read the value from memory every time as you've told it that the value might change without notice...

Another use is to map hardware ports.

On a microcontroller you might have some digital inputs which "appear" at a certain memory address. You can read them as if they were a variable but of course the value will potentially change all the time depending on the input signals. Declaring the value as volatile will indicate to the compiler that yes you actually do need to read this memory location every single time because it might have changed, and no you can't assume that it won't change unless you change it.

Unless you are using low level interrupts or some uses of threading then you don't need to use it.

EDIT: To be clear, volatile is NOT for synchronization between theads in standard c++, it only does a part of what is necessary. The last sentence in my original post could be misleading. The examples and stuff about hardware interrupts etc in my post are what volatile is for, it absolutely ISN'T for threading and don't even try to use it for that.

I originally wrote "some uses of threading" because on some platforms it might be sufficient to use volatile. This is BAD ADVICE in general but if you have a single core and all writes are visible to all "threads" then it might work for you. For example on a microcontroller with a simple interrupt based thread switching system it would likely "work" even though not guarenteed by the standard. But don't do it. In general it's just wrong, and c++11 has ways that actually work (remember this answer was written pre c++11)

like image 42
jcoder Avatar answered Oct 03 '22 14:10

jcoder