Possible Duplicate:
Volatile vs. Interlocked vs. lock
I am trying to understand situations when I would want to use the volatile keyword, vs Interlocked.
If I have a variable where every read from, and write to, that object is via Interlocked.Exchange, is that essentially the same thing as marking that variable as volatile?
private object _threadSafe;
private void Test()
{
var tmp = new object();
Interlocked.Exchange(ref tmp, _threadSafe); //read
Interlocked.Exchange(ref _threadSafe, "hi"); //write
}
If, instead of this, the _threadSafe object was marked as volatile and I removed the Interlocked's, would that be functionally equivalent? (Assume I am not dependent on atomic read/increment/writes, like incrementing a value).