Deadlock avoidance is a dynamic approach that requires the operating system to know in advance the maximum resource requirements of each process and to make careful allocation decisions that keep the system in a safe state—i.e., a state from which all processes can complete without ever entering a deadlock. Unlike prevention (which statically forbids one of the four necessary conditions) or detection (which lets deadlocks occur and then recovers), avoidance permits all four conditions but refuses resource requests that could lead to an unsafe state .
Principle of the Banker's Algorithm
Dijkstra’s Banker’s algorithm models processes as bank customers and resources as cash in the bank.
- Analogy: Each process declares a maximum claim, just as a customer has a maximum credit limit.
- Safe vs. Unsafe State: Before granting a request, the OS simulates allocation and checks if there exists a sequence in which every process can finish (“safe sequence”). If yes, the request is granted; otherwise, it is deferred to avoid entering a deadlock-prone (unsafe) state .
Data Structures in Banker's Algorithm
Let there be m resource types and n processes. The Banker’s algorithm maintains:
- Total\_Res\[1..m]: Total instances of each resource.
- Max\[n]\[m]: Maximum demand of each process for each resource.
- Alloc\[n]\[m]: Currently allocated instances to each process.
- Avail\[1..m]: Available instances = Total\_Res – ∑(Alloc rows).
- Need\[n]\[m]: Remaining need = Max – Alloc .
Safety Algorithm of Banker's Algorithm
To check if the system is in a safe state:
- Work ← Avail; Finish\[i] ← false for all i.
- Find a process Pᵢ such that Finish\[i] = false and Need\[i] ≤ Work.
- If found, Work ← Work + Alloc\[i]; Finish\[i] ← true; record Pᵢ in the safe sequence, repeat step 2.