In other words, can I do something with a volatile variable that could not also be solved with a normal variable and the Interlocked class?
views:
419answers:
5Yes - you can look at the value directly.
As long as you ONLY use the Interlocked class to access the variable then there is no difference. What volatile does is it tells the compiler that the variable is special and when optimizing it shouldn't assume that the value hasn't changed.
Takes this loop:
bool done = false;
...
while(!done)
{
... do stuff which the compiler can prove doesn't touch done...
}
If you set done
to true
in another thread you would expect the loop to exit. However - if done is not marked as volatile
then the compiler has the option to realize that the loop code can never change done
and it can optimize out the compare for exit.
This is one of the difficult things about multithread programming - many of the situations which are problems only come up in certain situations.
This is fairly complex topic. I find Joseph Albahari's writeup to be one of the more definitive and accurate sources for multithreading concepts in the .NET Framework that might help answer your question.
But, to quickly summarizes there is a lot of overlap between the volatile
keyword and the Interlocked
class as far as how they can be used. And of course both go way above and beyond what you can do with a normal variable.
I won't attempt to be an authority on this subject but I would highly recommend that you take a look at this article by the vaunted Jon Skeet.
Also take a look at the final part of this answer which details what volatile
should be used for.
Yes, you can gain some performance by using a volatile variable instead of a lock.
Lock is a full memory barrier which can give you the same characteristics of a volatile variable as well as many others. As has already been said volatile just ensures that in multi-threaded scenarios if a CPU changes a value in its cache line, the other CPUs sees the value immediately but do not ensure any locking semantic at all.
The thing is lock is a lot more powerful than volatile and you should use volatile when you can to avoid unnecessary locks.