Volatile Keyword in C++
I think Volatile keyword in C++ is not obvious and direct as other keyword like const,mutable etc. The main reason is we don’t know how Volatile works. We are told this keyword usually would be used to qulify the shared value in muitithreaded envoriment. But even though we need to take a lot of care to use this keyword. And The direct way to learn Volatile is through the assemble code.
Prerequiste
- I use VS2015 to do this expirement
- Turn on the optimization
Avoid from assigning register to the variable
- Normal variable without Volatile
We can see the compiler just do some optimization to move the eax to b, not from the real memory. Assume before b=a, a will be changed in another thread, but b can not get updated value. so this is the problem, that’s not what we want. So volatile can help us out. (by the way, if you application only get one thread, forget about the volatile).
We can see after a was declared as a volatile variable, the compiler will not force to get the a value from the memory.
No optimization
As we all know, the compiler will do some great job to improve the performance and reduce the size. But sometimes some optimization we want to avoid.
the result looks crazy, the compiler just generates one line assemble code for use , and this line gets nothing about the variable a and b. what if we declare the variable a and b as a volatile variable.
Execution Order
Sometimes the assemble code excution order is not the same as the order of your c++ code. that’s is a big problem for muitithreaded programming. Assume we gotta share two variables between two threads. one thread do things like the following piece of code.
and another thread do thing like this
that could be a risk if you turn on code optimization. sometimes the compiler will generate different order of code. even though you declare b as a volatile variable. so in this senario we prefer using something like mutex to keep the execution order.