Sweaty Imposter

Mutex / Lock

TechniqueConcurrencyJuniorMidUpdated
Mutual-exclusion primitive: at most one thread holds the lock at a time, serializing access to a critical section.

When to Use Mutex / Lock

Any shared mutable state touched by multiple threads where correctness depends on read-modify-write being atomic. Default first reach for senior backends before optimizing.

In Practice

Java's synchronized / ReentrantLock, Python's threading.Lock, Linux kernel spinlock_t and mutex_t. The JDK's ConcurrentHashMap segments used to be backed by per-segment ReentrantLocks.

Sketch

Java

private final ReentrantLock lock = new ReentrantLock();
private long balance;

public void deposit(long amount) {
    lock.lock();
    try {
        balance += amount;
    } finally {
        lock.unlock();
    }
}

How Mutex / Lock Comes Up in Interviews

Scenario

Two threads each do balance = balance + delta on a shared account. Sometimes the second update overwrites the first because both read the same old value. You need them serialized, the critical section is several statements, and you want simple readable code.

A mutex is the simplest correct answer for a multi-statement critical section. CAS works for a single word but rolling a CAS loop around several reads/writes gets ugly fast. Thread-local would break the 'shared account' invariant.