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?

有帮助吗?

解决方案

Interlocked has support at the CPU level, which can do the atomic operation directly.

For example, Interlocked.Increment is effectively an XADD, and compare and swap (ie: Interlocked.CompareExchange) is supported via the CMPXCHG instructions (both with a LOCK prefix).

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top