Qualcomm Interview Question
Software Engineer / DevelopersObjects declared as volatile are not used in certain optimizations because their values can change at any time. The system always reads the current value of a volatile object at the point it is requested, even if a previous instruction asked for a value from the same object. Also, the value of the object is written immediately on assignment.
When optimizing, the compiler must maintain ordering among references to volatile objects as well as references to other global objects. In particular,
A write to a volatile object (volatile write) has Release semantics; a reference to a global or static object that occurs before a write to a volatile object in the instruction sequence will occur before that volatile write in the compiled binary.
A read of a volatile object (volatile read) has Acquire semantics; a reference to a global or static object that occurs after a read of volatile memory in the instruction sequence will occur after that volatile read in the compiled binary.
This allows volatile objects to be used for memory locks and releases in multithreaded applications.
abt Volatile keyword and Optimizing Compiler..
How volatile key word works exactly ?
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
AFAIK, in regards to storage, there is no difference between variables declared as volatile and non volatile variables. So the variable may be on stack,heap or in the data section of executable, depending on how it gets defined. The volatile qualifier just tells the compiler that this variable may change in ways that are not apparent to you (for example by another thread of execution etc). The compiler then disables some optimizations(like caching the variable in a register).
- Jasmeet bagga April 16, 2010