Locks and Deadlocks

Tools that make threads take turns on shared data, and the ways they can get stuck forever.

What is it?

A lock makes a section of code run by only one thread at a time. A thread acquires the lock before touching shared data and releases it after. Any other thread that tries to acquire it waits. The code between acquire and release is the critical section.

Common kinds:

- Mutex (mutual exclusion): one holder at a time. - Semaphore: a counter allowing up to N holders, used to limit concurrency (for example, at most 10 open database connections). - Read-write lock: many readers at once, or one writer alone. Good for data that is read far more than it is written.

Locks introduce their own failure modes. A deadlock happens when threads wait on each other in a cycle, so none can ever proceed. Livelock is when threads keep reacting to each other and changing state, but none makes progress. Starvation is when a thread waits indefinitely because others keep getting the lock first.

For simple shared values, atomic operations such as compare-and-swap (CAS) avoid locks altogether. Data structures built only on atomics are called lock-free.

Explain like I'm 10

A mutex is a single-occupancy bathroom key. A semaphore is a parking lot with 10 spaces and a counter at the gate. A deadlock is two drivers on a one-lane bridge, each waiting for the other to back up. Livelock is two people in a corridor who keep stepping aside in the same direction.

Examples

Classic deadlock: two locks taken in opposite order (Python)

import threading

account_lock_a = threading.Lock()
account_lock_b = threading.Lock()

def transfer_a_to_b():
    with account_lock_a:
        with account_lock_b:      # waits for B...
            pass

def transfer_b_to_a():
    with account_lock_b:
        with account_lock_a:      # ...while this waits for A: deadlock
            pass

Fix: always acquire locks in one global order

def transfer(source, target, amount):
    first, second = sorted([source, target], key=lambda account: account.id)
    with first.lock:
        with second.lock:
            source.balance -= amount
            target.balance += amount

Every thread locks the lower id first, so a cycle of waiting is impossible. This breaks the circular-wait condition.

Compare-and-swap loop (Java)

AtomicInteger maxSeen = new AtomicInteger(Integer.MIN_VALUE);

void record(int value) {
    int current;
    do {
        current = maxSeen.get();
        if (value <= current) return;
    } while (!maxSeen.compareAndSet(current, value));  // retry if someone changed it
}

CAS writes the new value only if the variable still holds the value we read. If another thread changed it in between, CAS fails and we retry with the fresh value. No thread ever blocks.

How it works

How a mutex works. Under the hood, a mutex is an atomic flag. Acquiring tries an atomic CAS from "free" to "held". If that fails, the thread may spin briefly, then ask the OS to sleep it (Linux futexes do this) until the holder releases. Acquire and release also act as memory barriers, so writes made inside the critical section are visible to the next thread that takes the lock.

Semaphores keep a count. acquire decrements it and blocks at zero; release increments it and wakes a waiter. A semaphore with count 1 behaves like a mutex but has no notion of an owner.

The four Coffman conditions. A deadlock can only happen if all four hold: 1. Mutual exclusion: a resource can be held by only one thread. 2. Hold and wait: a thread holds one resource while waiting for another. 3. No preemption: resources can't be forcibly taken away. 4. Circular wait: a cycle of threads each waiting on the next.

Break any one and deadlock is impossible. In practice: impose a global lock order (breaks circular wait), acquire all locks at once or use tryLock with a timeout and back off (breaks hold and wait), or keep critical sections small and never call unknown code while holding a lock.

Livelock often comes from naive retry-on-conflict: both threads back off and retry at the same moment, forever. Randomized backoff fixes it. Starvation comes from unfair locks or priority scheduling; fair locks (FIFO) trade throughput for guaranteed progress. Priority inversion is a related problem: a low-priority thread holding a lock blocks a high-priority one.

Lock-free programming. CAS-based algorithms guarantee that some thread always makes progress, even if others are paused. They avoid deadlock but are hard to get right (the ABA problem: a value changes from A to B and back to A, so CAS wrongly succeeds). Use existing lock-free structures from your standard library rather than writing your own.

Deadlock (circular wait):

   Thread 1 --holds--> [Lock A]
      ^                    |
      |                 wanted by
   wanted by               v
   [Lock B] <--holds-- Thread 2

 Read-write lock:
   readers:  R R R R  (together)   |  writer: W (alone)
   a writer waits until all readers leave; readers wait while W holds it

Why does it exist?

Threads that share mutable state need a way to make multi-step updates appear atomic to everyone else. Hardware only provides atomicity for single words, so locks build larger atomic sections on top of those primitives. Deadlocks, livelock and starvation aren't separate features; they're the failure modes that come with any mechanism that makes threads wait.

When to use it

- Mutex to protect an invariant across several fields (a balance and a transaction log, a map and its size). - Read-write lock for read-heavy shared data like configuration or caches, after measuring that the mutex is actually contended. - Semaphore to cap concurrent access to a limited resource: connections, file handles, outbound API calls. - Atomics/CAS for single counters, flags, and reference swaps.

When not to use it

- Don't lock data that isn't shared; confine it to one thread instead. - Don't hold a lock while doing I/O, sleeping, or calling callbacks you don't control. That's how you get contention and surprise deadlocks. - Don't reach for read-write locks by default; they cost more than a mutex and only pay off when reads dominate and critical sections are long. - Don't write your own lock-free data structures in production unless you're an expert with a strong reason; use the standard library's concurrent collections. - For locks across machines, a local mutex is useless; you need a distributed lock with fencing tokens, or better, a design that avoids one.

Common mistakes

  • Acquiring the same pair of locks in different orders in different code paths, creating a deadlock that only appears under load.

  • Forgetting to release a lock when an exception is thrown. Use with, try/finally, defer, or RAII guards so release always happens.

  • Holding a lock during slow work (network calls, disk I/O), serializing the whole program behind it.

  • Re-acquiring a non-reentrant mutex in the same thread (for example, a locked method calling another locked method) and deadlocking on yourself.

  • Protecting writes with a lock but reading the same data without it, which still allows torn or stale reads.

Practice exercises

  1. Easy:

    Use a semaphore to limit a pool of 20 worker threads so that at most 3 of them are inside a simulated 'download' function at any moment. Log entries and exits to prove the limit holds.

  2. Medium:

    Implement the dining philosophers problem with 5 threads and 5 locks. Show that the naive version deadlocks, then fix it two different ways (lock ordering, and a semaphore allowing only 4 philosophers to sit).

  3. Hard:

    Implement a lock-free stack using compare-and-swap on the head pointer (Java AtomicReference or C++ std::atomic). Explain the ABA problem as it applies to your stack and how a tagged pointer or garbage collection avoids it.

Interview questions

What is the difference between a mutex and a semaphore?

A mutex allows one holder and has ownership: the thread that locked it must unlock it. A semaphore holds a count, allows up to N concurrent holders, and has no owner, so any thread can release. Semaphores are for limiting concurrency or signalling; mutexes are for mutual exclusion.

What are the four conditions for deadlock?

The Coffman conditions: mutual exclusion, hold and wait, no preemption, and circular wait. All four must hold simultaneously; preventing any one of them prevents deadlock.

How do you prevent deadlocks in practice?

Acquire locks in a consistent global order, hold as few locks as possible for as short a time as possible, never call external code while holding a lock, use tryLock with timeouts and back off, or redesign to avoid shared locks (message passing, single-owner data).

What is the difference between deadlock, livelock and starvation?

Deadlock: threads are blocked waiting on each other and nothing changes. Livelock: threads are active and keep changing state in response to each other, but none progresses. Starvation: the system progresses, but one thread never gets the resource because others keep winning.

When is a read-write lock better than a mutex?

When reads vastly outnumber writes and read critical sections are long enough that letting them run in parallel matters. For short critical sections or write-heavy data, the extra bookkeeping makes it slower than a plain mutex, and writer starvation is a risk with some implementations.

What is compare-and-swap?

An atomic CPU instruction: 'if this memory location still holds expected, set it to new and report success; otherwise report failure'. It's the building block for atomics, lock-free data structures, and the fast path of mutexes. Typical use is a retry loop: read, compute, CAS, retry on failure.

What is the ABA problem?

A thread reads value A, gets paused, another thread changes it to B and then back to A, and the first thread's CAS succeeds even though the state changed in between. In a lock-free stack this can corrupt the structure. Fixes include version-tagged pointers, hazard pointers, or relying on a GC that won't reuse a node's memory while it's referenced.

What is a reentrant lock?

A lock the same thread can acquire multiple times without deadlocking itself; it keeps a hold count and is released when the count returns to zero. Java's synchronized and ReentrantLock and Python's RLock are reentrant; Python's Lock and Go's sync.Mutex are not.

What is priority inversion?

A high-priority thread waits on a lock held by a low-priority thread, while medium-priority threads preempt the low-priority one, so the high-priority thread is effectively blocked by unrelated work. Priority inheritance temporarily raises the lock holder's priority to fix it. It famously affected the Mars Pathfinder lander.

Is lock-free always faster than using locks?

No. Lock-free algorithms avoid blocking and deadlock, but under heavy contention CAS retries waste CPU and cache-line bouncing hurts. An uncontended mutex is very cheap. Lock-free shines when threads must not block (real-time, signal handlers) or contention is moderate; measure before choosing.