How does Interlocked work and why is this faster than locking?

I just found out about a locked class and that it should be faster than just locking. Now this is all good and good, but I wonder how to implement it.

As far as I know, the only way to guarantee that an operation on a variable is atomic is to ensure that only one thread can access this variable at any given time. This is a lock.

I used a reflector to get the lock source, but it seems like it uses an 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 ran a few tests, and actually locking is twice as fast as just locking the object and increasing it.

How do they do it?

+6
source share
1 answer

Locking has support at the CPU level, which can perform an atomic operation directly.

For example, Interlocked.Increment is XADD , and comparisons and exchanges (i.e.: Interlocked.CompareExchange ) are supported using CMPXCHG instructions (both with the LOCK prefix).

+8
source

Source: https://habr.com/ru/post/953251/


All Articles