How the banker’s algorithm tests a safe state

Short answer: The banker’s algorithm avoids deadlock by refusing a resource request that would leave the system in an unsafe state. A state is safe when there exists an order of the processes such that each one can obtain its declared maximum with the resources free at its turn, finish, and release everything. The test is O(n²·m) for n processes and m resource types, a depth-first or greedy search for that order. The algorithm needs each process to declare a maximum in advance.


What the problem actually asks

Deadlock avoidance is not deadlock detection. Detection finds a cycle in a wait-for graph after the system is stuck. Avoidance refuses a request that might lead there. The banker’s test asks a sharper question: even if every process immediately demanded the rest of its maximum, is there still an order in which they can all finish? If yes, the state is safe. If no, the request is denied or the process must wait, even though a lucky future might have worked.

The maximum claims are the price of the test. A process that cannot name a maximum cannot be included. A process that overstates its maximum reduces concurrency. A process that understates it breaks the proof.


What the algorithm guarantees

If the system starts in a safe state and only safe requests are granted, every process can finish under the worst-case demand the claims allow. The safety test tries processes that can run to completion with the currently free resources, releases their allocation, and repeats. If every process is eliminated, the recorded order is a safe sequence. Time is O(n²·m) for a direct implementation. Extra memory is the allocation matrix, the maximum matrix, and the need matrix, which is maximum minus allocation.

An unsafe state is not a deadlock. It is a state where some future demand pattern deadlocks. Refusing it forgoes schedules that might have succeeded. That conservatism is the algorithm.


The working steps

  1. Store for each process its maximum claim and its current allocation. Need is the difference. Free is the vector of unallocated units.
  2. On a request, pretend to grant it: subtract from free, add to allocation, subtract from need. If the request exceeds need or free, reject it before the test.
  3. Search for a safe sequence. Repeatedly mark a process whose need is componentwise at most free, then add its allocation back to free.
  4. If every process is marked, accept the request and keep the new state. Otherwise roll back the pretended grant and deny the request.
  5. A granted request that is not followed by the real allocation update leaves the matrices lying. The pretend step and the commit step have to match.

Safety is a sufficient condition for deadlock freedom under the claimed maxima, not a necessary condition for every possible schedule. Detection after the fact is a wait-for graph. The banker’s algorithm is useless without truthful maxima. It is also a poor fit for interactive systems where maxima are unknown.


Approaches that look simpler and fail

Approach Why it fails when an unsafe state is treated as a deadlock
Abort processes whenever the safety test fails An unsafe state may still run to completion if processes do not all demand their maxima at once. The test refuses risk. It does not report a cycle that exists now.
Run the test without maxima Need is maximum minus allocation. Without a maximum the comparison with free has nothing to say about future demand.
Grant a request that exceeds the declared need because units are free The process violated its claim. The safety proof no longer applies, and the extra units can create a deadlock the test was not allowed to see.
Search for one process that can finish and stop A safe sequence includes every process. One runnable process does not make the rest safe.

Finding an actual deadlock is cycle detection in a wait-for graph. The banker’s algorithm is the avoidance test that looks for a safe sequence before granting a request.


A working example

This Python fragment grants a request only when a safe sequence still exists. One unit is free. Process A holds 1 and may still need 1. Process B holds 0 and may need 2. Giving the free unit to B leaves no safe sequence, so the request is denied. It prints deny.

# need, alloc
need = [[1], [2]]
alloc = [[1], [0]]
free = [1]

def safe(need, alloc, free):
    work = free[:]
    done = [False, False]
    for _ in range(2):
        progress = False
        for i in range(2):
            if not done[i] and need[i][0] <= work[0]:
                work[0] += alloc[i][0]
                done[i] = True
                progress = True
        if not progress:
            break
    return all(done)

# pretend B takes the free unit
need_b = [row[:] for row in need]
alloc_b = [row[:] for row in alloc]
need_b[1][0] -= 1
alloc_b[1][0] += 1
assert safe(need, alloc, free) and not safe(need_b, alloc_b, [0])
print("deny")

Where it is used

The banker’s algorithm is the textbook deadlock-avoidance test, and operating systems do not run it: a process rarely declares its maximum claim. Kernels avoid deadlock by lock ordering, or they detect a deadlock after it happens. The safe-state check remains the model of that resource question.


When you can drop this algorithm

Drop the banker’s algorithm when processes cannot declare maxima. Use detection and recovery, or a lock order that prevents cycles. Keep the safety test when maxima are real and refusing an unsafe request is acceptable.


Why this stays published

We publish this so a search for the banker’s algorithm returns the safe sequence and the distinction between an unsafe state and a deadlock. The banker’s algorithm grants a request only when the resulting state still has an order in which every process can finish within its declared maximum.

本文由 HoHo 與 AI 協作整理,最後更新於 2026 年 11 月 13 日。

Leave a Reply

Your email address will not be published. Required fields are marked *