Answer by HeSansi for Volatile vs. Interlocked vs. lock
I'm just here to point out the mistake about volatile in Orion Edwards' answer.He said:"If it is volatile, this just ensures the two CPUs see the same data atthe same time."It's wrong. In microsoft'...
View ArticleAnswer by V. S. for Volatile vs. Interlocked vs. lock
I would like to add to mentioned in the other answers the difference between volatile, Interlocked, and lock:The volatile keyword can be applied to fields of these types:Reference types.Pointer types...
View ArticleAnswer by zihotki for Volatile vs. Interlocked vs. lock
I second Jon Skeet's answer and want to add the following links for everyone who want to know more about "volatile" and Interlocked: Atomicity, volatility and immutability are different, part one -...
View ArticleAnswer by Zach Saw for Volatile vs. Interlocked vs. lock
Either lock or interlocked increment is what you are looking for.Volatile is definitely not what you're after - it simply tells the compiler to treat the variable as always changing even if the current...
View ArticleAnswer by Kenneth Xu for Volatile vs. Interlocked vs. lock
I did some test to see how the theory actually works: kennethxu.blogspot.com/2009/05/interlocked-vs-monitor-performance.html. My test was more focused on CompareExchnage but the result for Increment is...
View ArticleAnswer by Orion Edwards for Volatile vs. Interlocked vs. lock
Worst (won't actually work)Change the access modifier of counter to public volatileAs other people have mentioned, this on its own isn't actually safe at all. The point of volatile is that multiple...
View ArticleAnswer by Michael Damatov for Volatile vs. Interlocked vs. lock
"volatile" does not replace Interlocked.Increment! It just makes sure that the variable is not cached, but used directly.Incrementing a variable requires actually three operations:...
View ArticleAnswer by Rob Walker for Volatile vs. Interlocked vs. lock
lock(...) works, but may block a thread, and could cause deadlock if other code is using the same locks in an incompatible way.Interlocked.* is the correct way to do it ... much less overhead as modern...
View ArticleAnswer by Jon Skeet for Volatile vs. Interlocked vs. lock
EDIT: As noted in comments, these days I'm happy to use Interlocked for the cases of a single variable where it's obviously okay. When it gets more complicated, I'll still revert to locking...Using...
View ArticleAnswer by Lou Franco for Volatile vs. Interlocked vs. lock
Interlocked functions do not lock. They are atomic, meaning that they can complete without the possibility of a context switch during increment. So there is no chance of deadlock or wait.I would say...
View ArticleVolatile vs. Interlocked vs. lock
Let's say that a class has a public int counter field that is accessed by multiple threads. This int is only incremented or decremented.To increment this field, which approach should be used, and...
View Article