NVIDIA Interview Question
Software Engineer / Developersindicates that the variable can be modify from somewhere else and thus compiler will not apply any optimizations (if any could be applied ) to it
Usually the case while using threads....
Similar to transient keyword in Java
Correct me if im wrong
ususlly Volatile is used in shared memory, memory mapped hardware operation ,were we dont want compiler not to modify volatile variable
ususlly Volatile is used in shared memory, memory mapped hardware operation ,were we dont want compiler not to modify volatile variable
a working example can be as follows: suppose the attached printer to ur computer is memory mapped. So the controller takes some bytes in RAM to get and requests from/to the CPU. One of the valuable variables in printer controller is : control register . But coz of memory mapping it gets (say) stored at some memory location. So if we dont declare this control variable in our driver code then optimized compilers at run time will store it in local cache of CPU which leads to chaos. consider the case when CPU for some application want to command the printer for printing. so first it has to check the status of printer (busy/idle). But coz control variable is in cache , may be that printer just before 1 instruction back to app. instruction updated the control variable in RAM indicating busy signal which was not updated in cache . So CPU unknowingly kick off the spooled file to printer and the chaos happens. Tell me if i am wrong somewhere.
A lot of examples for volatile are very constructed, because most modern compilers won't optimize the code anymore in ways that you really need volatile with very few exceptions.
One real-world example I did find is a threadsafe implementation of the Singleton pattern. MSDN has an article on implementing threadsafe Singleton in C# using volatile to use double-checked locking the right way.
The usual four examples of volatile objects are:
- T.J. February 09, 20121. an object that is a memory-mapped I/O port
2. an object that is shared between multiple concurrent processes
3. an object that is modified by an asynchronous signal handler
4. an automatic storage duration object declared in a function that calls setjmp and whose value is changed between the call to setjmp and a corresponding call to longjmp
uw714doc.sco.com/en/SDK_cprog/_When_to_Use_volatile.html