lecture7-deadlock
lecture7-deadlock
• Implementation is subtle:
– Assume we can know whether a thread is waiting
and/or holding a lock
– Can we simply check each thread?
Deadlock detection
• Checking thread one by one is not correct
– Thread 1 holds lock L1
– Thread 1 waits on L2
– Check L1 (Thread 1 holds L1 and waits for L2)
– Thread 1 gets L2 and finally releases both L2 and L1
– Thread 2 holds lock L2
– Thread 2 waits on L1
– Check L2 (Thread 2 holds L2 and waits for L1)
– False alarm: Deadlock between Thread 1 and 2
Deadlock detection
• Checking threads one by one is not fully correct
• Checking must be done in an atomic way
– Option 1: Pause all threads (may be costly)
– Option 2: We will learn a solution later when
discussing distributed protocols
• Key idea:
– Each thread estimates the max number of each type of
resources it needs
– When a thread actually asks for a resource, check
whether granting the resource may create a deadlock in
the worst case.
Banker’s algorithm
• What is the worst case?
– Each thread actually asks for the maximal number of
each type of resources
k =1
end if
end for
End while
1 2 2 k =1
Max- Claimm atrixB = 1 2 1
1 1 1 0 0 2
CurrentNeedm atrixE = 1 1 0 = B − C
1 2 0 0 1 0
m atrixC = 0
CurrentAllocation 1 1
1 0 1
CurrentAvailmatrix D = (0 1 0) = A − Ck
n
k =1
0 0 1
CurrentNeedm atrixE = 1 1 0 = B − C
0 1 0
Banker’s algorithm example (3)
• The new state is safe
– P3 can complete (because E3 D) and thus can return
(1 0 1) to the pool of available resources
– D becomes (1 1 1); the outstanding needs of both P1
and P2 can be satisfied
Limitation
• Estimating the max resource is not easy
• Why?
– Order can break the cycle (cycle means no order)
Reality
• In practice, OS (e.g. Linux) or PL (C, Java, etc)
does not provide any mechanism to
avoid/prevent/detect deadlock automatically.