CodeBlanks Logo Icon CodeBlanks

Interlocked

C# course · Expert · Lesson 23/47

Learn atomic operations with Interlocked.

The Interlocked class

The Interlocked class provides atomic operations without a lock. Interlocked.Increment(ref n) increments n by one and the operation is atomic; even if another thread does it at the same time the result is correct.

Similarly Interlocked.Decrement, Interlocked.Add, Interlocked.Exchange and Interlocked.CompareExchange are available. It is much faster than lock because it uses a single CPU instruction.

Interlocked vs lock

Interlocked is ideal for simple single-step atomic operations. Using lock to increment a counter is costly; Interlocked.Increment does the same job much more cheaply.

But to make multiple operations atomic together, lock is still needed. Right choice: single variable -> Interlocked; multiple variables -> lock.

Exercise Increment a counter with Interlocked

Declare private static int _counter = 0;. In Main create 3 threads, each calling Interlocked.Increment(ref _counter); (once). Wait with Join. Finally print Console.WriteLine($"Counter: {_counter}");. (3 threads * 1 increment = 3 expected.)

Show example solution
{_counter}");
Example solution:
using System;
using System.Threading;

class Program
{
    private static int _counter = 0;

    static void Main()
    {
        Thread t1 = new Thread(() => { Interlocked.Increment(ref _counter); });
        Thread t2 = new Thread(() => { Interlocked.Increment(ref _counter); });
        Thread t3 = new Thread(() => { Interlocked.Increment(ref _counter); });
        t1.Start();
        t2.Start();
        t3.Start();
        t1.Join();
        t2.Join();
        t3.Join();
        Console.WriteLine($"Counter: {_counter}");
    }
}

Test yourself

  1. What does Interlocked.Increment do?

    • Increment with a lock
    • Starts a new thread
    • Atomic increment
    • Triggers a GC collection
    Show answer

    Atomic increment — Correct. Interlocked.Increment is an atomic increment.

  2. Match the Interlocked methods

    Interlocked.Increment
    Atomic +1
    Interlocked.Decrement
    Atomic -1
    Interlocked.Add
    Atomic add
    Interlocked.Exchange
    Atomic assign
  3. The Interlocked.Increment call

    Interlocked.____(ref n);
    Show answer
    Interlocked.Increment(ref n);

All lessons in Expert