Hardware Atomic Operations: `Interlocked` Class & Lock-Free Counters
1Concept
`System.Threading.Interlocked` utilizes CPU hardware lock bus prefix instructions (`LOCK XADD`, `LOCK CMPXCHG`) to perform atomic increments and compare-exchange operations in a single CPU cycle without operating system lock kernel transitions.
2Architecture Diagram
Thread 1 (Core 1) ──┐
├──> [ Hardware Bus LOCK CMPXCHG ] ──> Target Integer in RAM
Thread 2 (Core 2) ──┘ (Guaranteed Atomic Update without OS Locks!)3Code Example
C# 13 & .NET 9
using System;
using System.Threading;
using System.Threading.Tasks;
public class InterlockedDemo
{
private static long _requestCount = 0;
public static void Main()
{
Parallel.For(0, 100_000, i =>
{
// Hardware lock-free atomic increment
Interlocked.Increment(ref _requestCount);
});
Console.WriteLine($"Final Atomic Request Count: {_requestCount}");
}
}4Expected Output
Final Atomic Request Count: 100000
5Key Takeaways
- ✓Use `Interlocked.Increment`, `Decrement`, `Add`, and `CompareExchange` for high-performance lock-free counters.
- ✓`Interlocked` is ~20-50x faster than standard `lock(obj)` blocks.
- ✓`CompareExchange` enables lock-free optimistic spin loops.