Lesson 12 · Synchronization and deadlocks

Banker's Algorithm

Grant a request only if some ordering still lets every process finish. The test is cheap to state, costs O(m·n²) to run, and needs a number nobody usually has.

Banker's Algorithm concept diagramThe Work vector starts at Available = 3 3 2 and grows to 10 5 7. Between each pair of Work boxes a process whose Need fits under Work finishes and returns its Allocation: P1, P3, P4, P0, P2, which is the safe sequence.Work = Available, then every finisher hands its Allocation backAvailable3 3 2Work5 3 2Work7 4 3Work7 4 5Work7 5 5all done10 5 7P1need 1 2 2frees 2 0 0P3need 0 1 1frees 2 1 1P4need 4 3 1frees 0 0 2P0need 7 4 3frees 0 1 0P2need 6 0 0frees 3 0 2safe sequence: P1 → P3 → P4 → P0 → P2
1

Avoidance, Not Prevention

The banker's algorithm, proposed by Dijkstra for operating systems, is a deadlock avoidance algorithm. It sits between prevention, which removes one of the four Coffman conditions outright, and detection, which lets deadlock happen and then recovers.

Avoidance takes a third route: allow all four conditions, but refuse any allocation that would move the system into a state from which deadlock is possible. Every request is tested before it is granted.

The name comes from a bank that must never lend so much that some customer cannot be paid. The bank may hold less cash than the sum of all credit lines; what matters is that there is always some order in which every customer can be satisfied.

  • Prevention: break a condition, always
  • Avoidance: allow the conditions, refuse unsafe allocations
  • Detection: allow deadlock, find it, recover
2

The Four Matrices

  1. Available[m] — unallocated units per resource type.
  2. Max[n][m] — declared worst-case demand per process.
  3. Allocation[n][m] — what is held right now.
  4. Need[n][m] = Max − Allocation — what could still be asked for.

For n processes and m resource types the algorithm keeps four structures.

Need is the whole point. It answers the only question that matters: what else could this process still ask for before it is finished? A process whose Need is met can definitely complete, and when it does it returns everything it holds.

The Max matrix is also the algorithm's practical weakness — it requires every process to declare its worst-case demand before it starts, which most real programs cannot do.

The worked state: 5 processes, resources A B C, Available = (3, 3, 2)
ProcessAllocationMaxNeed = Max − Allocation
P00 1 07 5 37 4 3
P12 0 03 2 21 2 2
P23 0 29 0 26 0 0
P32 1 12 2 20 1 1
P40 0 24 3 34 3 1
  • Need is derived, not tracked separately
  • Allocation + Need = Max, always
  • Max must be declared in advance
3

The Safety Algorithm

  1. Initialise — Work = Available, Finish[i] = false for all i.
  2. Find a process i with Finish[i] = false and Need[i] ≤ Work.
  3. Release — Work = Work + Allocation[i], then Finish[i] = true.
  4. Repeat from step 2 until no such i exists.
  5. Decide — safe if every Finish[i] is true, unsafe otherwise.

The safety algorithm answers one question: does a sequence exist in which every process can finish? If yes the state is safe; if no it is unsafe.

Those five lines are the whole algorithm. Each pass looks for a process it can afford to finish, then pretends it finished and hands back everything it held — which may make the next process affordable.

If every Finish[i] is true the state is safe and the order in which they were picked is a safe sequence. If some remain false the state is unsafe.

Note precisely what unsafe means: not that deadlock has occurred, and not even that it will. It means deadlock has become possible, and the algorithm refuses to enter that territory at all.

  • Unsafe ≠ deadlocked — it means deadlock is reachable
  • The safe sequence is a witness, not a schedule
  • Cost: O(m·n²)
Key reference

Terms, operations, and practical uses

Core vocabulary

  • Safe stateSome order exists in which every process can obtain its full Need and finish.
  • Safe sequenceThat order, e.g. P1 → P3 → P4 → P0 → P2. A witness that the state is safe, not a schedule.
  • NeedMax − Allocation: what a process may still request before it finishes.
  • Avoidance vs prevention vs detectionAvoidance refuses unsafe grants; prevention removes a Coffman condition; detection lets deadlock happen and recovers.

Costs

  • Safety checkO(m·n²): up to n passes, each comparing n Need vectors of length m.
  • Request checkO(m) for Request ≤ Need and ≤ Available, then one safety check: O(m·n²).
  • SpaceO(n·m) for the Max, Allocation and Need matrices, plus O(m) for Available.
Implementation

Code in Python, C++ and Java

ORDER = ["P0", "P1", "P2", "P3", "P4"]
MAXIMUM = {
    "P0": (7, 5, 3),
    "P1": (3, 2, 2),
    "P2": (9, 0, 2),
    "P3": (2, 2, 2),
    "P4": (4, 3, 3),
}


def need(process, allocation):
    """Need = Max - Allocation: what the process could still ask for."""
    return tuple(MAXIMUM[process][i] - allocation[process][i] for i in range(3))


def fits(want, have):
    return all(w <= h for w, h in zip(want, have))


def safe_sequence(available, allocation):
    """Return a safe sequence, or None if the state is unsafe.

    Sweep P0..P4 repeatedly; any process whose Need fits in Work finishes
    and returns its Allocation. A pass with no progress means unsafe.
    """
    work = available
    finished = []
    progressed = True
    while progressed:
        progressed = False
        for process in ORDER:
            if process not in finished and fits(need(process, allocation), work):
                work = tuple(work[i] + allocation[process][i] for i in range(3))
                finished.append(process)
                progressed = True
    return finished if len(finished) == len(ORDER) else None


def request(process, amount, available, allocation):
    """Grant only if the resulting state is still safe.

    Returns (verdict, available, allocation): the new state if granted,
    the old one unchanged if not.
    """
    if not fits(amount, need(process, allocation)):
        return "error: exceeds declared Max", available, allocation
    if not fits(amount, available):
        return "wait: not enough available", available, allocation

    trial_available = tuple(available[i] - amount[i] for i in range(3))
    trial_allocation = dict(allocation)
    trial_allocation[process] = tuple(
        allocation[process][i] + amount[i] for i in range(3)
    )

    sequence = safe_sequence(trial_available, trial_allocation)
    if sequence is None:
        return "unsafe, rolled back, waits", available, allocation
    return "granted, safe " + " -> ".join(sequence), trial_available, trial_allocation


def main():
    allocation = {
        "P0": (0, 1, 0),
        "P1": (2, 0, 0),
        "P2": (3, 0, 2),
        "P3": (2, 1, 1),
        "P4": (0, 0, 2),
    }
    available = (3, 3, 2)

    sequence = safe_sequence(available, allocation)
    print("initial state: safe " + " -> ".join(sequence))

    verdict, available, allocation = request("P1", (1, 0, 2), available, allocation)
    print(f"P1 requests (1, 0, 2): {verdict}")

    verdict, available, allocation = request("P0", (0, 2, 0), available, allocation)
    print(f"P0 requests (0, 2, 0): {verdict}")


if __name__ == "__main__":
    main()
#include <array>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using Vec = std::array<int, 3>;
using Alloc = std::map<std::string, Vec>;
const std::vector<std::string> ORDER = {"P0", "P1", "P2", "P3", "P4"};
const Alloc MAXIMUM = {
{
    "P0", {7, 5, 3}
}, {"P1", {3, 2, 2}}, {"P2", {9, 0, 2}},
{
    "P3", {2, 2, 2}
}, {"P4", {4, 3, 3}},
};
// Need = Max - Allocation: what the process could still ask for.
Vec need(const std::string& p, const Alloc& allocation) {
    Vec n {
    };
    for (int i = 0; i < 3; i++) n[i] = MAXIMUM.at(p)[i] - allocation.at(p)[i];
    return n;
}
bool fits(const Vec& want, const Vec& have) {
    for (int i = 0; i < 3; i++) {
        if (want[i] > have[i]) return false;
    }
    return true;
}
std::string join(const std::vector<std::string>& seq) {
    std::string out;
    for (size_t i = 0; i < seq.size(); i++) out += (i ? " -> " : "") + seq[i];
    return out;
}
// Sweep P0..P4 repeatedly; a pass with no progress means unsafe.
// Returns the safe sequence, or an empty vector if the state is unsafe.
std::vector<std::string> safeSequence(Vec work, const Alloc& allocation) {
    std::vector<std::string> finished;
    std::map<std::string, bool> done;
    bool progressed = true;
    while (progressed) {
        progressed = false;
        for (const auto& p : ORDER) {
            if (!done[p] && fits(need(p, allocation), work)) {
                for (int i = 0; i < 3; i++) work[i] += allocation.at(p)[i];
                finished.push_back(p);
                done[p] = progressed = true;
            }
        }
    }
    if (finished.size() < ORDER.size()) return {};
    return finished;
}
// Grant only if the resulting state is still safe; on success the
// state is updated in place, otherwise it is left unchanged.
std::string request(const std::string& p, const Vec& amount, Vec& available, Alloc& allocation) {
    if (!fits(amount, need(p, allocation))) return "error: exceeds declared Max";
    if (!fits(amount, available)) return "wait: not enough available";
    Vec trialAvailable = available;
    Alloc trialAllocation = allocation;
    for (int i = 0; i < 3; i++) {
        trialAvailable[i] -= amount[i];
        trialAllocation[p][i] += amount[i];
    }
    auto sequence = safeSequence(trialAvailable, trialAllocation);
    if (sequence.empty()) return "unsafe, rolled back, waits";
    available = trialAvailable;
    allocation = trialAllocation;
    return "granted, safe " + join(sequence);
}
int main() {
    Alloc allocation = {
    {
        "P0", {0, 1, 0}
    }, {"P1", {2, 0, 0}}, {"P2", {3, 0, 2}},
    {
        "P3", {2, 1, 1}
    }, {"P4", {0, 0, 2}},
    };
    Vec available = {3, 3, 2};
    std::cout << "initial state: safe " << join(safeSequence(available, allocation)) << '\n';
    std::cout << "P1 requests (1, 0, 2): " << request("P1", {1, 0, 2}, available, allocation) << '\n';
    std::cout << "P0 requests (0, 2, 0): " << request("P0", {0, 2, 0}, available, allocation) << '\n';
}
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
class Main {
    static final String[] ORDER = {"P0", "P1", "P2", "P3", "P4"};
    static final Map<String, int[]> MAXIMUM = new LinkedHashMap<>();
    static {
        MAXIMUM.put("P0", new int[] {7, 5, 3});
        MAXIMUM.put("P1", new int[] {3, 2, 2});
        MAXIMUM.put("P2", new int[] {9, 0, 2});
        MAXIMUM.put("P3", new int[] {2, 2, 2});
        MAXIMUM.put("P4", new int[] {4, 3, 3});
    }
    // Need = Max - Allocation: what the process could still ask for.
    static int[] need(String p, Map<String, int[]> allocation) {
        int[] n = new int[3];
        for (int i = 0; i < 3; i++) n[i] = MAXIMUM.get(p)[i] - allocation.get(p)[i];
        return n;
    }
    static boolean fits(int[] want, int[] have) {
        for (int i = 0; i < 3; i++) {
            if (want[i] > have[i]) return false;
        }
        return true;
    }
    // Sweep P0..P4 repeatedly; a pass with no progress means unsafe.
    // Returns the safe sequence, or null if the state is unsafe.
    static List<String> safeSequence(int[] available, Map<String, int[]> allocation) {
        int[] work = available.clone();
        List<String> finished = new ArrayList<>();
        boolean progressed = true;
        while (progressed) {
            progressed = false;
            for (String p : ORDER) {
                if (!finished.contains(p) && fits(need(p, allocation), work)) {
                    for (int i = 0; i < 3; i++) work[i] += allocation.get(p)[i];
                    finished.add(p);
                    progressed = true;
                }
            }
        }
        return finished.size() == ORDER.length ? finished : null;
    }
    // Grant only if the resulting state is still safe; on success the
    // state is updated in place, otherwise it is left unchanged.
    static String request(String p, int[] amount, int[] available, Map<String, int[]> allocation) {
        if (!fits(amount, need(p, allocation))) return "error: exceeds declared Max";
        if (!fits(amount, available)) return "wait: not enough available";
        int[] trialAvailable = available.clone();
        Map<String, int[]> trialAllocation = new LinkedHashMap<>();
        for (Map.Entry<String, int[]> e : allocation.entrySet()) {
            trialAllocation.put(e.getKey(), e.getValue().clone());
        }
        for (int i = 0; i < 3; i++) {
            trialAvailable[i] -= amount[i];
            trialAllocation.get(p)[i] += amount[i];
        }
        List<String> sequence = safeSequence(trialAvailable, trialAllocation);
        if (sequence == null) return "unsafe, rolled back, waits";
        System.arraycopy(trialAvailable, 0, available, 0, 3);
        allocation.putAll(trialAllocation);
        return "granted, safe " + String.join(" -> ", sequence);
    }
    public static void main(String[] args) {
        Map<String, int[]> allocation = new LinkedHashMap<>();
        allocation.put("P0", new int[] {0, 1, 0});
        allocation.put("P1", new int[] {2, 0, 0});
        allocation.put("P2", new int[] {3, 0, 2});
        allocation.put("P3", new int[] {2, 1, 1});
        allocation.put("P4", new int[] {0, 0, 2});
        int[] available = {3, 3, 2};
        System.out.println("initial state: safe "
        + String.join(" -> ", safeSequence(available, allocation)));
        System.out.println("P1 requests (1, 0, 2): "
        + request("P1", new int[] {1, 0, 2}, available, allocation));
        System.out.println("P0 requests (0, 2, 0): "
        + request("P0", new int[] {0, 2, 0}, available, allocation));
    }
}
Watch it run

Step through it

Running on 5 processes, 3 resource types, Available = (3, 3, 2); then P1 requests (1, 0, 2) and P0 requests (0, 2, 0)

AllocationMaxNeed
P00 1 07 5 37 4 3
P12 0 03 2 21 2 2
P23 0 29 0 26 0 0
P32 1 12 2 20 1 1
P40 0 24 3 34 3 1
Available3 3 2unallocated units of A, B, C
Step 1

The starting state

Five processes, three resource types A, B and C. Allocation is what each process holds now. Max is the most it may ever demand, declared in advance, which is the algorithm's big assumption. Need = Max − Allocation: P0 needs (7,5,3) − (0,1,0) = (7,4,3).

Output
1 / 14
4

The Resource Request Algorithm

The resource request algorithm runs every time a process asks for more. Suppose P1 requests (1, 0, 2). Three checks run in order, and all three must pass.

First, Request ≤ Need? P1's Need is (1,2,2) and (1,0,2) ≤ (1,2,2) — yes. A process asking beyond its declared Max is an error, not a wait.

Second, Request ≤ Available? Available is (3,3,2) and (1,0,2) ≤ (3,3,2) — yes. Otherwise P1 simply waits; the state has not changed.

Third, pretend to grant it and run the safety algorithm on the resulting state. Available becomes (2,3,0), P1's Allocation (3,0,2) and its Need (0,2,0). The sweep still finds the sequence P1 → P3 → P4 → P0 → P2, so the state is safe and the request is granted.

Now suppose P0 requests (0, 2, 0) in that new state. Both checks pass: (0,2,0) ≤ Need (7,4,3) and ≤ Available (2,3,0). But the trial state has Available (2,1,0) and P0's Need becomes (7,2,3). No process fits: P1 needs 2 of B, P3 needs 1 of C, and the rest need more A than is free. The sweep stalls before its first pick, so the state is unsafe: the trial is rolled back and P0 waits, even though the two units it asked for were physically free.

  • Request ≤ Need, else error
  • Request ≤ Available, else wait
  • Trial grant must leave a safe state, else roll back and wait
5

Limits, and Where It Fits

The algorithm is correct and the cost is modest — O(m·n²) per request. It is still almost never deployed, for reasons that have nothing to do with its correctness.

It needs Max declared in advance. A text editor cannot state its worst-case memory before the user opens a file. Without an accurate Max the test is meaningless.

It assumes a fixed set of processes and resources. Real systems create and destroy both continuously, and every change invalidates the analysis.

It is also conservative by construction: it refuses allocations that would probably have been fine, because it reasons about what could happen rather than what will. Most operating systems use the ostrich approach instead — ignore deadlock, and reboot on the rare occasion it happens.

When every resource type has a single instance, a cheaper test does the same job: a resource-allocation graph with claim edges. A request is granted only if turning its claim edge into an assignment edge leaves the graph without a cycle.

Where it does appear is in settings that match its assumptions: fixed embedded workloads, real-time systems with declared budgets, and transaction managers where every resource is known in advance.

  • Needs worst-case demand up front — usually unknowable
  • Assumes a static process and resource set
  • Conservative: refuses allocations that would have been safe
  • One instance per resource type: claim edges and a cycle check replace the matrices
  • Used in embedded and real-time systems, rarely elsewhere