Sub topic 2
Prevention: breaking one Coffman condition
This chapter assumes you know processes, threads, locks, and matrices. You should also be able to compare two vectors element by element. A deadlock is a state in which processes wait for each other forever.
Prevention: breaking one Coffman condition
A deadlock needs all four Coffman conditions at once: mutual exclusion, hold and wait, no preemption, and circular wait. Prevention removes one condition by design, so a deadlock cannot form.
- Circular wait: Number every resource. Require each process to request resources in increasing order. A cycle of waiting cannot form.
- Hold and wait: Require a process to request all its resources at once. This wastes resources and can starve some processes.
- No preemption: Take resources away from a waiting process. This works only for resources whose state can be saved, such as CPU registers, but not for a printer.
The code below uses the circular-wait rule. Both threads take lock A before lock B, so neither can hold B while waiting for A.
import threading
lock_a = threading.Lock()
lock_b = threading.Lock()
def task():
with lock_a: # always acquire A first
with lock_b: # then B
pass # use both resources
threads = [threading.Thread(target=task) for _ in range(2)]
for t in threads:
t.start()
for t in threads:
t.join()
print("finished without deadlock")Safe and unsafe states
A state is safe when the system can finish every process in some order, called a safe sequence. A state is unsafe when no such order exists. An unsafe state is not yet a deadlock, but it may lead to one. The Banker's algorithm avoids unsafe states.
The safety algorithm, step by step
Given Available, Allocation, and Max, compute Need = Max minus Allocation. Then:
- Set Work equal to Available. Mark every process unfinished.
- Find an unfinished process i whose Need[i] is less than or equal to Work in every element.
- Set Work = Work + Allocation[i], and mark process i finished.
- Repeat until no process fits. The state is safe if every process is finished.
Banker's algorithm: granting or delaying a request
When process i requests a vector Request, the system does the following:
- If Request exceeds Need[i], reject it as an error.
- If Request exceeds Available, the process waits.
- Otherwise, pretend to grant it. Run the safety algorithm. Keep the grant if the state is safe, or roll it back and delay the process if not.
Take the textbook state with Available = (3, 3, 2). Process P1 requests (1, 0, 2). Its Need is (1, 2, 2), so the request fits. After the pretend grant, Available becomes (2, 3, 0). The safe sequence is P1, P3, P4, P0, P2, so the grant is allowed.
Exercise
Exercise
In the same state, P4 requests (3, 3, 0). Should the request be granted?
Show answer
No. Its Need is (4, 3, 1), and Available (3, 3, 2) covers the request. After the pretend grant, Available is (0, 0, 2). No process's Need fits in (0, 0, 2), so the state is unsafe. The request is delayed.