I just know that volatile keyword is to restrict the
compiler from doing some optimizations, which is not required. Mostly
Global variables within a multi-threaded application will be declared
as volatile.
I want to know How volatile key word works exactly ??
Will the volatile variable be stored in Cache ????
How it is getting the updated value every time ????
Will it be possible to access Memory by bypassing the
Cache ???
Thanks & Regards,
RamSen.
Cache is hardware dependent. Will probably be stored in cache. You
have to mark uncacheable memory using hardware specific calls.
From the C++ standard 7.1.5.1/8:
"volatile is a hint to the implementation to avoid aggressive
optimization involving the object because the value of the object might
be changed by means undetectable by an implementation."
In other words, "don't store this value in a register, because it could
change out from underneath you". It has nothing to do with the hardware
cache.
You said it exactly correctly above. It prevents the compiler
from holding the variable's value in a register. it forces the
compiler to generate a fetch of the value from memory every time
the variable is referenced, and if the value is modified while
in a register, it is immediately stored to memory.
>
> Will the volatile variable be stored in Cache ????
Not just as a result of the volatile keyword, no.
>
> How it is getting the updated value every time ????
By generating code to re-fetch the variable *every* time.
>
> Will it be possible to access Memory by bypassing the
> Cache ???
Not by using the volatile keyword.
I think all these questions about caching come because the volatile
keyword is sometimes documented as stopping the compiler-generated
code from using the CPU registers as a cache. It's not the same
cache being discussed as the CPU-managed data or instruction
caches. The idea here is the optimization of treating the CPU
registers as a value cache, which is disabled by the volatile keyword.
> Thanks & Regards,
> RamSen.
>