Sub topic 8
The safety algorithm, step by step
This chapter assumes you know what a safe state is (the previous chapter), and that you can read vectors and matrices and compare two vectors element by element. For vectors, X <= Y means X[j] <= Y[j] for every position j. If even one position fails, the comparison is false.
The safety algorithm answers one question: given the current allocation state, is there at least one order in which every process can run to completion? It never runs the processes. It only pretends to, using bookkeeping.
The data it works on
Let n be the number of processes and m the number of resource types. The system keeps four structures.
| Name | Shape | Meaning |
|---|---|---|
| Available | vector of length `m` | Free instances of each resource type right now |
| Max | `n x m` matrix | The most of each type a process may ever request (its declared claim) |
| Allocation | `n x m` matrix | Instances of each type a process holds right now |
| Need | `n x m` matrix | What a process may still request: `Need = Max - Allocation` |
Max is declared in advance and Allocation changes as the system runs. Need is derived from those two, so you compute it first.
Work and Finish
The algorithm uses two temporary structures.
Workis a vector of lengthm. It starts as a copy of Available and represents the resources free in the imagined future.Finishis a vector ofnbooleans, all false at the start.Finish[i]becomes true when processihas been imagined finished.
The algorithm has four steps.
- Set
Work = AvailableandFinish[i] = falsefor everyi. - Find a process
iwithFinish[i] == falseandNeed[i] <= Work. If none exists, go to step 4. - Set
Work = Work + Allocation[i]andFinish[i] = true, then go back to step 2. - If
Finish[i]is true for everyi, the state is safe. Otherwise it is unsafe.
The justification for step 3 is that process i can obtain everything it might still ask for, so it can finish. When it finishes it releases everything it holds, and Work grows by Allocation[i].
A worked example
Take 5 processes and three resource types A, B and C. The system has 10, 5 and 7 instances of them. The current state is:
| Process | Allocation (A B C) | Max (A B C) | Need (A B C) |
|---|---|---|---|
| P0 | 0 1 0 | 7 5 3 | 7 4 3 |
| P1 | 2 0 0 | 3 2 2 | 1 2 2 |
| P2 | 3 0 2 | 9 0 2 | 6 0 0 |
| P3 | 2 1 1 | 2 2 2 | 0 1 1 |
| P4 | 0 0 2 | 4 3 3 | 4 3 1 |
Available is (3, 3, 2). As a check, the allocations sum to (7, 2, 5), and adding Available gives (10, 5, 7), the system totals. Do this check on every exam question, because it catches transcription errors.
Trace the algorithm, scanning processes from P0 upward each time:
Work = (3,3,2). P0 needs(7,4,3), which does not fit. P1 needs(1,2,2), which fits. Finish P1, soWork = (3,3,2) + (2,0,0) = (5,3,2).- Restart the scan. P0 does not fit. P2 needs
(6,0,0), and 6 > 5, so it does not fit. P3 needs(0,1,1), which fits. Finish P3, soWork = (5,3,2) + (2,1,1) = (7,4,3). - P0 needs
(7,4,3), which equalsWork, so it fits. The ordering of the scan matters only for which sequence you report, so the code below instead takes P4 in the same pass. P4 needs(4,3,1), which fits. Finish P4, soWork = (7,4,3) + (0,0,2) = (7,4,5). - P0 fits. Finish P0, so
Work = (7,4,5) + (0,1,0) = (7,5,5). - P2 needs
(6,0,0), which fits. Finish P2, soWork = (7,5,5) + (3,0,2) = (10,5,7).
Every process finished, so the state is safe. The safe sequence is <P1, P3, P4, P0, P2>. The final Work equals the system total, which must always happen when every process finishes.
The algorithm in code
The function below repeats the scan until a full pass finishes no process. That is slightly different from restarting the scan after each finish, but it reaches the same verdict. The second call uses a single resource type with 10 instances, where the state is unsafe.
def is_safe(available, allocation, need):
n = len(allocation)
m = len(available)
work = list(available)
finish = [False] * n
order = []
progress = True
while progress:
progress = False
for i in range(n):
if not finish[i] and all(need[i][j] <= work[j] for j in range(m)):
for j in range(m):
work[j] += allocation[i][j]
finish[i] = True
order.append(i)
progress = True
return all(finish), order
# Classic textbook state: 5 processes, 3 resource types (A, B, C)
allocation = [[0, 1, 0], [2, 0, 0], [3, 0, 2], [2, 1, 1], [0, 0, 2]]
max_need = [[7, 5, 3], [3, 2, 2], [9, 0, 2], [2, 2, 2], [4, 3, 3]]
available = [3, 3, 2]
need = [[max_need[i][j] - allocation[i][j] for j in range(3)] for i in range(5)]
print(is_safe(available, allocation, need)) # (True, [1, 3, 4, 0, 2])
# One resource type, 10 instances: Available is 1
alloc1 = [[5], [2], [2]]
need1 = [[5], [2], [7]]
print(is_safe([1], alloc1, need1)) # (False, [])In the second state, no process has a Need that fits in one free instance (the needs are 5, 2 and 7), so nothing can start the chain. The state is unsafe even though no process is blocked yet. If Available were 3 (a 12-instance system), P1 would finish first, then P0, then P2, and the state would be safe.
Properties worth knowing
Cost
Each pass over the processes costs up to n comparisons of m numbers, and at most n processes can finish, so there are at most n productive passes. The total is O(m * n^2) operations. This is the figure GATE questions ask for.
The safe sequence is not unique
Several orders may work. In the example above, P3 could be chosen before P1, since (0,1,1) also fits in (3,3,2). So a question asking "which of the following is a safe sequence?" is checked by simulating each option in order. A sequence is valid only if each process's Need fits in the Work available at that moment, where Work includes releases from the processes earlier in that sequence.
The verdict does not depend on the order chosen
Finishing a process only ever increases Work, and a larger Work never makes another process fit worse. So if any complete order exists, a greedy choice cannot ruin it. This is why the algorithm needs no backtracking, and why it is safe to pick any fitting process at step 2.
Safe, unsafe and deadlocked
Safe means a completion order exists. Unsafe means none exists, so deadlock is possible but not certain: processes might happen to release resources early or never ask for their full Max. Deadlocked means processes are already blocked in a cycle of waiting. Every deadlocked state is unsafe, but an unsafe state is not necessarily deadlocked.
Common errors
- Subtracting wrongly when building Need, so one row is off. Check
Allocation + Need = Maxfor each row. - Comparing only one column. The vector comparison needs every resource type to fit, not just the largest.
- Declaring the state unsafe after one failed scan. A failed scan only means that no process fits right now. Finish whichever process fits and scan again.
- Stopping when Work is large. The goal is that every process finishes, not that Work reaches some target.
- Treating an unsafe state as a deadlock. The next chapter (the Banker's algorithm) uses this distinction to delay requests, and it is only valid if you keep the two apart.
Exercise
A system has one resource type with 8 instances and three processes. P0 holds 3 and may need up to 6 in total. P1 holds 2 and may need up to 3 in total. P2 holds 2 and may need up to 8 in total. One instance is free. Is the state safe? If so, give a safe sequence.
Show answer
Need is P0 = 3, P1 = 1, P2 = 6. Check the total: 3 + 2 + 2 + 1 = 8, which matches. Start with Work = 1. Only P1 fits (Need 1 <= 1), so Work becomes 1 + 2 = 3. P0 fits (Need 3 <= 3), so Work becomes 3 + 3 = 6. P2 fits (Need 6 <= 6), so Work becomes 6 + 2 = 8. The state is safe, with safe sequence P1, P0, P2.
Exercise
In the 5-process example of this chapter, suppose Available were (1, 1, 0) instead of (3, 3, 2), with Allocation and Max unchanged. Is any process able to start the chain?
Show answer
No. The Need rows are P0 (7,4,3), P1 (1,2,2), P2 (6,0,0), P3 (0,1,1) and P4 (4,3,1). With Work = (1,1,0), P3 needs 1 unit of C but none is free. P1 needs 2 units of B and 2 of C, which is too many. P2 needs 6 of A, P0 needs 7 of A, and P4 needs 4 of A. Nothing fits, so Finish stays all false and the state is unsafe.