ConcurrencyC#verifiedVerified

Mutex / Lock Pattern in C#

Guarantee that only one thread at a time can access a shared resource by requiring threads to acquire an exclusive lock before proceeding.

How to Implement the Mutex / Lock Pattern in C#

1Step 1: Shared resource protected by a lock

public class BankAccount
{
    private readonly object _lock = new();
    private decimal _balance;

    public BankAccount(decimal initial) => _balance = initial;

    public decimal Balance
    {
        get { lock (_lock) { return _balance; } }
    }

2Step 2: Mutex ensures only one thread modifies balance at a time

    public bool Withdraw(decimal amount)
    {
        lock (_lock)
        {
            if (_balance < amount) return false;
            _balance -= amount;
            return true;
        }
    }

    public void Deposit(decimal amount)
    {
        lock (_lock)
        {
            _balance += amount;
        }
    }
}

// Usage:
// var account = new BankAccount(1000m);
// Parallel.For(0, 10, _ => account.Withdraw(100m));
// Console.WriteLine(account.Balance); // 0

Mutex / Lock Pattern Architecture

hourglass_empty

Rendering diagram...

lightbulb

Mutex / Lock Pattern in the Real World

A single-occupancy public restroom with a door latch is a perfect mutex. The latch (lock) ensures only one person (thread) occupies the restroom (critical section) at a time. Anyone who finds the door locked must wait outside; when the occupant leaves and unlatches the door, one waiting person may enter.