TExcelTAD
Home › Operating Systems: Linux & Windows › Synchronization & Deadlocks

Synchronization & Deadlocks

When threads share memory, or processes share a file or a shared-memory region, some sequences of steps must not be interleaved. The piece of code that touches the shared data is a critical section, and the operating system provides the tools that make sure only one thread (or a controlled number of threads) is inside at a time. Getting this wrong gives race conditions; getting it wrong the other way gives deadlocks.

The building blocks

Primitive Idea Linux Windows
Atomic operation One indivisible CPU instruction (lock xadd, compare-and-swap) __atomic_*, C11 <stdatomic.h> InterlockedIncrement, InterlockedCompareExchange
Spinlock Loop until the lock is free; for very short sections, mostly inside kernels spin_lock() (kernel), pthread_spin_lock KeAcquireSpinLock (kernel)
Mutex Lock with an owner; waiters sleep pthread_mutex_t (built on futex) SRWLOCK, CRITICAL_SECTION; kernel Mutex object across processes
Semaphore A counter: wait decrements (sleeps at 0), signal increments sem_t (sem_wait/sem_post) CreateSemaphore, WaitForSingleObject/ReleaseSemaphore
Condition variable Sleep until another thread says "something changed" pthread_cond_t CONDITION_VARIABLE (SleepConditionVariableSRW)
Reader/writer lock Many readers or one writer pthread_rwlock_t SRWLOCK (shared/exclusive)
Event A flag threads can wait on eventfd CreateEvent (manual/auto-reset)
File lock Lock a file or byte range flock, fcntl(F_SETLK) LockFileEx

Futexes and SRW locks: fast in the common case

A system call costs hundreds of nanoseconds, too much for a lock that is usually free. Both kernels therefore split locks in two:

  • Linux futex ("fast user-space mutex"): the lock is an integer in ordinary memory. Taking a free lock is one atomic compare-and-swap in user mode, no kernel involved. Only when the lock is contended does the thread call futex(FUTEX_WAIT) to sleep, and the unlocker calls futex(FUTEX_WAKE). glibc's mutexes, condition variables and semaphores are all built on futexes.
  • Windows SRW locks and critical sections work the same way: an atomic operation in user mode, and a kernel wait (via keyed events, or WaitOnAddress, the direct futex equivalent added in Windows 8) only under contention. Kernel objects such as CreateMutex are slower but have names and work across processes.

Semaphores and the producer–consumer problem

The classic exercise: a producer puts items into a bounded buffer, a consumer takes them out. Three semaphores coordinate them: empty counts free slots, full counts filled slots, and mutex (a semaphore with count 1) protects the buffer itself. Real thread timing is not reproducible, so this simulation is its own little scheduler: each thread is a generator, a wait on a zero semaphore blocks the thread, and a signal wakes the first blocked waiter. The scheduler runs ready threads in round-robin order, a few steps each.

python · try it yourself
from collections import deque

class Semaphore:
    def __init__(self, name, value):
        self.name, self.value, self.waiters = name, value, deque()

def producer(n):
    for i in range(1, n + 1):
        yield ("wait", empty); yield ("wait", mutex)
        buffer.append(f"item{i}"); log("producer", f"put item{i}   buffer={list(buffer)}")
        yield ("signal", mutex); yield ("signal", full)

def consumer(n):
    for _ in range(n):
        yield ("wait", full); yield ("wait", mutex)
        item = buffer.popleft(); log("consumer", f"took {item}  buffer={list(buffer)}")
        yield ("signal", mutex); yield ("signal", empty)

def log(who, msg):
    print(f"t={clock:02d} {who:<9}{msg}")

buffer = deque()
empty, full, mutex = Semaphore("empty", 2), Semaphore("full", 0), Semaphore("mutex", 1)
threads = {"producer": producer(4), "consumer": consumer(4)}
ready, clock = deque(["producer", "consumer"]), 0
SLICE = 3                                    # steps per turn

while ready:
    name = ready.popleft()
    status = "ready"
    for _ in range(SLICE):
        clock += 1
        try:
            op, sem = next(threads[name])
        except StopIteration:
            status = "done"
            break
        if op == "wait":
            if sem.value > 0:
                sem.value -= 1
            else:                            # no permit: sleep until someone signals
                sem.waiters.append(name)
                status = "blocked"
                print(f"t={clock:02d} {name:<9}blocks on {sem.name}")
                break
        elif sem.waiters:                    # signal: hand the permit straight to a waiter
            ready.append(sem.waiters.popleft())
        else:
            sem.value += 1
    if status == "ready":
        ready.append(name)
print("done, buffer empty:", not buffer)
t=03 producer put item1   buffer=['item1']
t=04 consumer blocks on full
t=08 consumer blocks on mutex
t=09 producer put item2   buffer=['item1', 'item2']
t=11 producer blocks on empty
t=12 consumer took item1  buffer=['item2']
t=16 producer put item3   buffer=['item2', 'item3']
t=19 consumer took item2  buffer=['item3']
t=23 producer put item4   buffer=['item3', 'item4']
t=26 consumer took item3  buffer=['item4']
t=32 consumer took item4  buffer=[]
done, buffer empty: True

The buffer never holds more than two items, the consumer never takes from an empty buffer, and each thread sleeps (instead of spinning) while it cannot proceed.

Deadlock

A deadlock is a set of threads each waiting for a resource another one holds, so none can ever continue. The textbook example: thread 1 locks A then wants B; thread 2 locks B then wants A. Four conditions (Coffman, 1971) must all hold:

  1. Mutual exclusion: a resource is held by one thread at a time.
  2. Hold and wait: a thread holds one resource while waiting for another.
  3. No preemption: resources can't be taken away.
  4. Circular wait: a cycle exists in the wait-for graph.
text
     holds            wants
  T1 -----> [lock A] <----- T2
   ^                         |
   |  wants          holds   |
   +------- [lock B] <-------+

Breaking any one condition prevents deadlock. In practice programmers break circular wait by always taking locks in a fixed global order (the Linux kernel documents its lock ordering; lockdep checks it at run time).

Detection: find a cycle

An OS or a database can detect deadlock by building the wait-for graph (an edge T1 → T2 means "T1 waits for a resource T2 holds") and looking for a cycle. Databases such as PostgreSQL and SQL Server do exactly this and abort one victim transaction.

python · try it yourself
def wait_for_graph(holds, wants):
    owner = {res: t for t, rs in holds.items() for res in rs}
    return {t: [owner[r] for r in rs if r in owner and owner[r] != t] for t, rs in wants.items()}

def find_cycle(graph):
    state = {}                                    # 1 = on the current path, 2 = finished
    def dfs(node, path):
        state[node] = 1
        for nxt in graph.get(node, []):
            if state.get(nxt) == 1:
                return path[path.index(nxt):] + [nxt]
            if nxt not in state and (cyc := dfs(nxt, path + [nxt])):
                return cyc
        state[node] = 2
        return None
    for start in sorted(graph):
        if start not in state and (cyc := dfs(start, [start])):
            return cyc
    return None

holds = {"T1": ["A"], "T2": ["B"], "T3": ["C"], "T4": []}
wants = {"T1": ["B"], "T2": ["C"], "T3": ["A"], "T4": ["A"]}
g = wait_for_graph(holds, wants)
print("wait-for graph:", g)
cycle = find_cycle(g)
print("deadlock:", " -> ".join(cycle) if cycle else "none")

wants["T3"] = []                                   # T3 stops waiting for A
print("after T3 releases its request:", find_cycle(wait_for_graph(holds, wants)) or "no deadlock")
wait-for graph: {'T1': ['T2'], 'T2': ['T3'], 'T3': ['T1'], 'T4': ['T1']}
deadlock: T1 -> T2 -> T3 -> T1
after T3 releases its request: no deadlock

T4 is waiting too, but it is not in the cycle: it will run once T1 finishes. Only the cycle members are stuck.

Avoidance: the Banker's algorithm

Dijkstra's Banker's algorithm avoids deadlock by refusing any request that could lead to an unsafe state. Each process declares its maximum need in advance; a state is safe if there is some order in which every process can get its maximum, finish and give everything back.

python · try it yourself
available = [3, 3, 2]                         # free units of resources A, B, C
maximum = {"P0": [7, 5, 3], "P1": [3, 2, 2], "P2": [9, 0, 2], "P3": [2, 2, 2], "P4": [4, 3, 3]}
alloc   = {"P0": [0, 1, 0], "P1": [2, 0, 0], "P2": [3, 0, 2], "P3": [2, 1, 1], "P4": [0, 0, 2]}

def safe_sequence(available, alloc):
    need = {p: [m - a for m, a in zip(maximum[p], alloc[p])] for p in maximum}
    work, done, order = list(available), set(), []
    while len(done) < len(maximum):
        for p in maximum:
            if p not in done and all(n <= w for n, w in zip(need[p], work)):
                work = [w + a for w, a in zip(work, alloc[p])]   # p finishes and releases everything
                done.add(p); order.append(p)
                break
        else:
            return None
    return order

print("initial state safe sequence:", safe_sequence(available, alloc))

def request(p, req):
    new_avail = [a - r for a, r in zip(available, req)]
    if any(x < 0 for x in new_avail):
        return f"{p} asks {req}: must wait (not enough free)"
    new_alloc = dict(alloc, **{p: [a + r for a, r in zip(alloc[p], req)]})
    seq = safe_sequence(new_avail, new_alloc)
    return f"{p} asks {req}: " + (f"GRANTED, safe order {seq}" if seq else "DENIED, state would be unsafe")

print(request("P1", [1, 0, 2]))
print(request("P0", [0, 2, 0]))
print(request("P4", [3, 3, 0]))
initial state safe sequence: ['P1', 'P3', 'P0', 'P2', 'P4']
P1 asks [1, 0, 2]: GRANTED, safe order ['P1', 'P3', 'P0', 'P2', 'P4']
P0 asks [0, 2, 0]: GRANTED, safe order ['P3', 'P1', 'P0', 'P2', 'P4']
P4 asks [3, 3, 0]: DENIED, state would be unsafe

Each request is checked on its own against the initial state. P4's request could be satisfied from the free units, but it would leave only [0, 0, 2] free, and from there no process can be sure of reaching its maximum, so the banker says no even though nothing is deadlocked yet.

Banker's algorithm is elegant but rare in general-purpose OSes: programs don't know their maximum needs and the check is expensive. Linux and Windows do neither avoidance nor general detection for application locks: they leave deadlock prevention to programmers (lock ordering, timeouts such as pthread_mutex_timedlock or WaitForSingleObject(h, 5000)) and debugging tools (Linux lockdep for the kernel, Helgrind and ThreadSanitizer for programs; Windows Driver Verifier, WinDbg's !locks, and Wait Chain Traversal, which Resource Monitor's Analyze wait chain uses).

File locks between processes

Processes coordinate through lock files too. Linux's flock command wraps a command in an exclusive lock; a second attempt with -n (non-blocking) fails immediately while the lock is held:

bash · try it yourself
touch job.lock
flock job.lock sleep 1 &
sleep 0.3
flock -n job.lock echo "got the lock" || echo "lock busy: another instance is running"
wait
flock -n job.lock echo "got the lock after the first one finished"
lock busy: another instance is running
got the lock after the first one finished

On Windows a file opened without sharing (FILE_SHARE_NONE) can't be opened by anyone else ("The process cannot access the file because it is being used by another process"), and LockFileEx locks byte ranges.

Learn more: Threads · Inter-Process Communication · OS Exercises

Test yourself

Why is a Linux futex fast when the lock is free?

  1. It disables interrupts
  2. Taking it is a single atomic instruction in user mode, with no system call
  3. The kernel caches it in the TLB
  4. It uses a spinlock in the kernel

Which Coffman condition does 'always lock A before B' break?

  1. Mutual exclusion
  2. Hold and wait
  3. No preemption
  4. Circular wait

What does the Banker's algorithm do with a request that would leave the system in an unsafe state?

  1. Grants it and detects deadlock later
  2. Kills the requesting process
  3. Makes the process wait (denies it for now)
  4. Preempts resources from another process