Sub topic 8
The Safety Algorithm, Step by Step
Assume you know processes, resource instances, directed graphs, and element-wise comparison of vectors. This chapter uses the Banker's model, where each process declares its maximum possible demand for every resource type.
What the safety algorithm checks
A state is safe if the operating system can find an order in which every process can obtain its remaining resources, finish, and release all resources it holds. The order is called a safe sequence.
A safe state may have waiting processes, but it guarantees that the system can avoid deadlock. An unsafe state is not necessarily deadlocked. It means that no completion order can be guaranteed using the declared maximum demands.
For each process and resource type, calculate:
Need = Max - Allocation
The algorithm uses these vectors:
| Structure | Meaning |
|---|---|
| Available | Instances not currently allocated |
| Allocation | Instances currently held by each process |
| Max | Maximum total claim of each process |
| Need | Additional instances each process may still request |
The step-by-step procedure
- Set
Work = Available. - Set every process's
Finishvalue toFalse. - Find an unfinished process whose
Needis no greater thanWorkin every resource type. - Pretend that this process finishes. Add its allocated resources to
Work:
Work = Work + Allocation
- Set its
Finishvalue toTrueand record it in the safe sequence. - Repeat until every process finishes or no eligible process remains.
- If every
Finishvalue isTrue, the state is safe. Otherwise, it is unsafe.
The comparison in step 3 is element-wise. For example, Need = [1, 2, 0] fits Work = [1, 3, 2], but it does not fit Work = [2, 1, 2] because the second component is too large.
Worked example
Consider the classic state with resources A, B, and C:
Available = [3, 3, 2]Allocation:- P0:
[0, 1, 0] - P1:
[2, 0, 0] - P2:
[3, 0, 2] - P3:
[2, 1, 1] - P4:
[0, 0, 2]
The resulting Need matrix is:
| Process | Need A | Need B | Need C |
|---|---|---|---|
| P0 | 7 | 4 | 3 |
| P1 | 1 | 2 | 2 |
| P2 | 6 | 0 | 0 |
| P3 | 0 | 1 | 1 |
| P4 | 4 | 3 | 1 |
Start with Work = [3, 3, 2].
- P1 fits because
[1, 2, 2]fits. After P1 finishes,Work = [5, 3, 2]. - P3 fits. Then
Work = [7, 4, 3]. - P4 fits. Then
Work = [7, 4, 5]. - P0 fits. Then
Work = [7, 5, 5]. - P2 fits. Then all processes finish.
Therefore, [P1, P3, P4, P0, P2] is a safe sequence.
Common errors
- Comparing only the total resource count instead of every component.
- Treating an unsafe state as proof that deadlock already exists.
- Forgetting to add
Allocationback toWork. - Requiring one fixed process order. Any valid safe sequence is sufficient.
Exercise
If Work = [2, 1] and an unfinished process has Need = [1, 2], can the process be selected?
Show answer
No. Its second resource need, 2, exceeds Work's second component, 1.