What is the difference in volatile in c# and c? I was asked this in one 开发者_如何学JAVAinterview.
The article mentioned in this blog post by Herb Sutter explains the things concisely and clearly and compares the usage and meaning of volatile in C, C++, Java and C#.
There are a couple of good questions and answers on this very site also:
- How to illustrate usage of volatile keyword in C#
- Usage of volatile specifier in C/C++/Java
- What is the “volatile” keyword used for?
- c++ volatile multithreading variables
- volatile and multithreading?
- Why is volatile needed in c?
EDIT: to not confuse anyone here is the "exact link" to the DDJ article mentioned in the initial link(which is a link to Herb Sutter's blog).
Also this article by Nigel Jones explains the volatile keyword in the context of embedded C programming. As this question seems to have popped up in an interview this other article by the same author is one of my favorites("exact link") and has another good explanation of volatile in the C world.
In C volatile tells the compiler not to optimize access to a variable:
int running = 1;
void run() {
while (running) {
// Do something, but 'running' is not used at all within the loop.
}
}
Normally the compiler may translate 'while (running)' in this case to just 'while (1)'. When the 'running' variable is marked as volatile, the compiler is forced to check the variable each time.
Important is to understand that for C 'volatile' only restricts the compiler to optimize, while your hardware (i.e. the CPU caches, instruction pipeline, etc) may still reorder memory access. There is no way your C compiler will tell your hardware not to optimize. You have to do it yourself (e.g. by using a memory barrier).
As far as I know (but I'm not completely sure) the C# specification takes this a bit further:
- If you write to a volatile variable, it is guaranteed that all memory accesses that you do before it are completed.
- If you read from a volatile variable, it is guaranteed that all memory accesses that you do after it are not completed before the read of the volatile varable is completed.
精彩评论