below is the source code with my comment for Interlocked:
public static class Interlocked {
// Int32 old = location;
// if (location == comparand) location = value;
// return old;
public static Int32 CompareExchange(ref Int32 location, Int32 value, Int32 comparand);
public static long Read(ref long location)
{
return Interlocked.CompareExchange(ref location, 0, 0);
}
}
I don't understand why Read calls Interlocked.CompareExchange(ref location, 0, 0)?
long location can be any number, why it is compared with 0?
Primary reason for use of
Interlocked.CompareExchange()method it is to ensure reading 64-bit value is atomic on 32-bit systems. Reading 64-bit value on 64-bit system is atomic by default.That is also why
Interlocked.Read()method only acceptsUint64andInt64parameters.Interlocked.CompareExchange()method is atomic operation that compares original value stored inlocation1withcomparandparameter to make sure the value we want to exchange was not changed by other thread having access to that variable. If the value was not changed, then it is replaced, otherwise nothing happens, but always the original value stored inlocation1is returned.So, the
Read()method actually leveraging above written by trying to compare 0 with value stored inlocation1and based on that comparison either replaces the value or not, but returning the original value.Which might be translated into something like
That is why
Read()method usesCompareExchange()method internally as anytime you useCompareExchange()you get original value and if you pass same values asvalueandcomparandyou never get into situation exchange actually happens. Either values are different and exchange is not going to happen at all or values are same and exchange is about to happen, but you are exchanging 0 for 0.