How Interlocked Ensures Atomicity

2025-03-18

This article was created with the assistance of ChatGPT

Low-Level CPU Instructions: The Interlocked class uses atomic CPU instructions that are executed as indivisible units. These CPU instructions, like Compare-and-Swap (CAS) or Test-and-Set, ensure that the operation is performed entirely or not at all, with no interference from other threads. These instructions are implemented in hardware, meaning that once a thread starts the operation, it cannot be interrupted until it is complete.

Lock-Free Mechanism: The atomic operations provided by Interlocked do not require traditional locking mechanisms (such as lock or mutexes). Instead, the underlying hardware guarantees that the operation is completed in an atomic manner. This is beneficial for performance because it avoids the overhead of acquiring and releasing locks.

Memory Barriers (Fences): To prevent other threads from accessing or modifying the shared data while an atomic operation is being performed, Interlocked ensures the use of memory barriers. Memory barriers ensure that all the operations on memory that happen before or after the atomic operation are properly ordered, preventing thread reordering and ensuring visibility of the operation across all threads.

Atomic Operations on Simple Types: The Interlocked class supports atomic operations on integral types (like int, long, and bool) and provides methods for:

  • Interlocked.CompareExchange: Compares the current value of a variable with a specified value, and if they are equal, it replaces it with a new value.
  • Interlocked.Add: Adds a specified value to a variable and stores the result atomically.
  • Interlocked.Exchange: Sets a variable to a specified value and returns its original value.
  • Interlocked.Decrement: Decreases a variable’s value by one.
  • Interlocked.Increment: Increases a variable’s value by one.

Example – Atomic Addition: Consider the operation Interlocked.Add(ref counter, 1). Here’s how it works atomically:

  • The counter variable is accessed by the CPU using an atomic instruction, ensuring that no other thread can read or modify counter during the operation.
  • The value of counter is incremented by 1, and the updated value is written back to memory.
  • No other thread can observe the increment operation in progress. Either it is fully completed, or it does not happen at all.

If multiple threads try to increment counter simultaneously, the atomic nature of Interlocked.Add guarantees that only one thread performs the addition at any given time, without any thread seeing an inconsistent value of counter.

For further reading on Interlocked and thread safety in .NET, refer to the official Microsoft documentation on Interlocked and Concurrency in .NET.

Leave a comment