Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Interlocked work and why is it faster than lock? [duplicate]

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?

like image 466
Arsen Zahray Avatar asked Sep 05 '13 15:09

Arsen Zahray


1 Answers

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).

like image 104
Reed Copsey Avatar answered Oct 27 '22 00:10

Reed Copsey