I just learned of interlocked class and that it is supposed to be faster than simply locking. Now, this is all nice and good, but I'm curious as to implementation.
As far as I know, the only way to ensure that operation on a variable is done atomically is to ensure that only one thread can access that variable at any moment in time. Which is locking.
I've used reflector to get the source of Interlocked, but it seems that it uses external method to do all its work:
[MethodImpl(MethodImplOptions.InternalCall), ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)]
internal static extern int ExchangeAdd(ref int location1, int value);
I've run some tests, and Interlocked in fact is twice as fast as simply lock the object and increment it.
How are they doing it?