Skip to content
Concept ยท Software Development

Deadlock in Operating System: Conditions, Prevention and Banker's Algorithm

Younus FardeenBy Younus FardeenUpdated 1 Dec 20269 min read
Short answer

A deadlock is a state where a set of processes are each waiting for a resource held by another in the set, so none can proceed. It needs four conditions together: mutual exclusion, hold and wait, no preemption and circular wait. Break any one to prevent it, or use Banker's algorithm to avoid unsafe states.

On this pageWhat is deadlock, and the four necessary conditionsA runnable deadlock demo with timeout detectionThe resource-ordering fixPrevention vs avoidance vs detectionBanker's algorithm with executed outputFrequently asked questions

Deadlock is a favourite operating system question because it can be asked at three levels: define it, name the four conditions, then run Banker's algorithm on a table. This page covers all three, and everything runnable was executed on 1 December 2026 with Python 3.9.6.

It builds on the thread and lock ideas in process vs thread. If you are preparing for a software role, the same bug shows up as stuck database transactions and stuck workers in real systems, which the backend developer roadmap treats as production skills. For wider interview prep, see the system design interview guide.

What is deadlock, and the four necessary conditions

A deadlock happens when two or more processes (or threads) wait forever for resources that the others hold. The classic picture: process 1 holds the printer and wants the scanner, process 2 holds the scanner and wants the printer. Neither can finish, so neither will ever release what the other needs.

Four conditions must hold at the same moment. They are often called the Coffman conditions after the 1971 paper that listed them. All four are necessary, so removing any one makes deadlock impossible.

ConditionMeaningExample
Mutual exclusionA resource can be used by only one process at a timeA lock, a printer, a write latch on a row
Hold and waitA process holds one resource while waiting for anotherHolds lock A, requests lock B
No preemptionA resource cannot be forcibly taken; only the holder releases itThe OS will not snatch a held mutex
Circular waitA cycle of processes, each waiting for a resource the next one holdsP1 waits for P2, P2 waits for P1

Do not confuse deadlock with two neighbours. Starvation is one process being denied a resource repeatedly while others make progress. Livelock is processes that keep changing state in response to each other but still make no progress. In a deadlock, nothing moves at all.

A runnable deadlock demo with timeout detection

Two threads take two locks. In the first run they take them in opposite order, which creates a circular wait. Normally acquire() would block forever, so the demo uses acquire(timeout=1): if the second lock is not available within a second, the thread reports a probable deadlock instead of hanging. The second run uses the same order for both threads.

import threading, time

lock_a, lock_b = threading.Lock(), threading.Lock()

def worker(name, first, second, results):
    with first:
        time.sleep(0.2)                       # both workers now hold one lock each
        if second.acquire(timeout=1):         # timeout turns a silent hang into a detectable event
            second.release()
            results[name] = "finished"
        else:
            results[name] = "TIMEOUT: probable deadlock"

def demo(title, order1, order2):
    results = {}
    t1 = threading.Thread(target=worker, args=("T1",) + order1 + (results,))
    t2 = threading.Thread(target=worker, args=("T2",) + order2 + (results,))
    t1.start(); t2.start(); t1.join(); t2.join()
    print(title, dict(sorted(results.items())))

if __name__ == "__main__":
    demo("opposite order (A then B / B then A):", (lock_a, lock_b), (lock_b, lock_a))
    demo("same order     (A then B / A then B):", (lock_a, lock_b), (lock_a, lock_b))

Output:

opposite order (A then B / B then A): {'T1': 'TIMEOUT: probable deadlock', 'T2': 'TIMEOUT: probable deadlock'}
same order     (A then B / A then B): {'T1': 'finished', 'T2': 'finished'}

Be precise about what the timeout shows. It detects a thread that has waited too long, which is a strong sign of deadlock but could also be a very slow holder. Production systems use timeouts together with logging, because a hung process with no log line is the hardest version of this bug.

The resource-ordering fix

The second run above is the fix. Give every lock a fixed global rank and always acquire in rank order (A before B, everywhere). Then no cycle can form: a thread holding B would never be waiting for A. This removes the circular wait condition, and it is the cheapest prevention technique a programmer controls.

  • Document the lock order next to the lock definitions, and review code that takes two locks.
  • Hold as few locks as possible, for as short a time as possible.
  • Use try-lock with timeout as a safety net, not as the main design.
  • In databases, access tables in a consistent order inside transactions; most engines also detect a deadlock and abort one transaction, so applications should be ready to retry.

Prevention vs avoidance vs detection

Operating systems handle deadlock in four ways. Prevention and avoidance stop it from happening. Detection and recovery allow it to happen, then fix it. The fourth, the ostrich approach, is to ignore it and rely on a restart. General-purpose systems such as Linux and Windows largely leave application-level deadlock to the programmer.

ApproachIdeaCostUsed when
PreventionMake one of the four conditions impossible (for example require all resources up front, or impose a lock order)Lower resource use, possible starvationYou control how resources are requested
AvoidanceGrant a request only if the system stays in a safe state (Banker's algorithm)Needs each process's maximum demand in advance; runs a check on every requestFixed, known workloads
Detection and recoveryAllow deadlock, find cycles in a wait-for graph, then kill or roll back a process or preempt a resourceLost work; detection overheadDatabases and systems where deadlock is rare
Ignore (ostrich)Assume it is rare enough to restart when it happensNone until it happensMost desktop and server operating systems

How each condition can be broken

  • Mutual exclusion: make resources shareable (read-only files). Often impossible for printers and write locks.
  • Hold and wait: request everything at once, or release held resources before asking for more.
  • No preemption: allow the OS to take resources from a waiting process.
  • Circular wait: order resources and request in increasing order.

Banker's algorithm with executed output

Banker's algorithm (Dijkstra) is the standard avoidance method. Each process declares a maximum claim for each resource type. The system tracks Allocation (held now), Need (maximum minus allocation) and Available. A state is safe if there is some order in which every process can get its remaining need, finish and release its resources. A request is granted only if the state after granting is still safe.

The code below uses the standard five-process, three-resource textbook example, with total instances A=10, B=5, C=7 and the data stored as lists. Each request is tested against the original state independently.

def is_safe(available, allocation, need):
    work, done, order = available[:], [False] * len(allocation), []
    while len(order) < len(allocation):
        for i, (alloc, nd) in enumerate(zip(allocation, need)):
            if not done[i] and all(n <= w for n, w in zip(nd, work)):
                work = [w + a for w, a in zip(work, alloc)]   # P_i finishes and releases everything
                done[i] = True; order.append(f"P{i}")
                break
        else:
            return False, order                               # nobody can finish: unsafe
    return True, order

def request(pid, req, available, allocation, maximum):
    need = [[m - a for m, a in zip(mx, al)] for mx, al in zip(maximum, allocation)]
    if any(r > n for r, n in zip(req, need[pid])): return "refused: asks more than its declared maximum"
    if any(r > a for r, a in zip(req, available)): return "wait: not enough free right now"
    avail2 = [a - r for a, r in zip(available, req)]
    alloc2 = [row[:] for row in allocation]; alloc2[pid] = [a + r for a, r in zip(alloc2[pid], req)]
    need2 = [[m - a for m, a in zip(mx, al)] for mx, al in zip(maximum, alloc2)]
    ok, order = is_safe(avail2, alloc2, need2)
    return ("granted, safe order " + " -> ".join(order)) if ok else "denied: would leave an unsafe state"

# Classic textbook example: 5 processes, resource types A, B, C
maximum    = [[7,5,3],[3,2,2],[9,0,2],[2,2,2],[4,3,3]]
allocation = [[0,1,0],[2,0,0],[3,0,2],[2,1,1],[0,0,2]]
available  = [3,3,2]
need = [[m - a for m, a in zip(mx, al)] for mx, al in zip(maximum, allocation)]
print("Need matrix:", need)
print("Safe now?  ", is_safe(available, allocation, need))
print("P1 asks [1,0,2]:", request(1, [1,0,2], available, allocation, maximum))
print("P4 asks [3,3,0]:", request(4, [3,3,0], available, allocation, maximum))
print("P0 asks [0,2,0]:", request(0, [0,2,0], available, allocation, maximum))

Output:

Need matrix: [[7, 4, 3], [1, 2, 2], [6, 0, 0], [0, 1, 1], [4, 3, 1]]
Safe now?   (True, ['P1', 'P3', 'P0', 'P2', 'P4'])
P1 asks [1,0,2]: granted, safe order P1 -> P3 -> P0 -> P2 -> P4
P4 asks [3,3,0]: denied: would leave an unsafe state
P0 asks [0,2,0]: granted, safe order P3 -> P1 -> P0 -> P2 -> P4

Reading it: the starting state is safe, with finishing order P1, P3, P0, P2, P4. P1's request is granted because a safe order still exists afterwards. P4's request of [3,3,0] is denied even though the resources are free right now, because after granting it nobody could finish. That is the key idea: avoidance sometimes makes a process wait when resources exist, to protect the future. In an exam, show the Need matrix, then the step-by-step Work vector as each process finishes.

Banker's algorithm is rarely used in real operating systems because processes seldom know their maximum demand in advance. Say that in an interview, since it separates understanding from memorising. For the networking side of waiting and timeouts, see TCP vs UDP.

Frequently asked questions

What are the four conditions for deadlock?

Mutual exclusion, hold and wait, no preemption, and circular wait. All four must hold at once for a deadlock to occur. If you can make any one of them impossible, for example by always acquiring locks in the same order to remove circular wait, deadlock cannot happen.

What is the difference between deadlock prevention and deadlock avoidance?

Prevention changes the rules so at least one of the four conditions can never hold. Avoidance leaves the rules alone but checks each resource request against what each process may still need, and grants it only if the system stays in a safe state, as Banker's algorithm does.

What is a safe state in Banker's algorithm?

A state is safe if there is at least one ordering of the processes in which each can obtain its remaining maximum need from the available resources plus what earlier processes release, finish, and release in turn. A safe state guarantees no deadlock; an unsafe state only means deadlock is possible.

How is deadlock detected?

The system builds a wait-for or resource-allocation graph and looks for a cycle. With single-instance resources a cycle means deadlock. With multiple instances it runs a detection algorithm similar to the safety check. Applications often use timeouts to notice stuck waits.

How do you recover from a deadlock?

Either terminate one or more processes in the cycle, or preempt a resource from one and roll that process back. Databases usually pick a victim transaction, abort it and let the application retry. Choosing the victim by cost, such as work already done, limits the lost effort.

What is the difference between deadlock and starvation?

In deadlock, a group of processes wait on each other and none can ever proceed. In starvation, one process waits indefinitely because others keep getting priority, while the system as a whole still makes progress. Ageing, which raises a waiting process's priority over time, fixes starvation.

Learn this with mentors

Programmes for builders and engineers with admissions open: live classes, mentors and project work.

Continue learning

Concept

Process vs thread

Process vs thread with timed Python demos and interview answers

7 min read
Interview prep

System design interview preparation

A 45-minute framework, core concepts, 10 classic problems and a 4-week plan

11 min read
Roadmap

Backend developer roadmap

Pick a stack, then SQL, APIs, auth, queues and Docker, in order

5 min read