ch08 Deadlocks
ch08 Deadlocks
ch08 Deadlocks
Chapter 8
Deadlocks
◆ System Model
◆ Deadlock in Multithreaded Applications
◆ Deadlock Characterization
◆ Methods for Handling Deadlocks
◆ Deadlock Prevention
◆ Deadlock Avoidance
◆ Deadlock Detection
◆ Recovery from Deadlock
/* thread one runs in this function */ /* thread two runs in this function */
void *do_work_one(void *param) void *do_work_two(void *param)
{ {
pthread_mutex_lock(&first_mutex); pthread_mutex_lock(&second_mutex);
pthread_mutex_lock(&second_mutex); pthread_mutex_lock(&first_mutex);
/* /*
* Do some work * Do some work
*/ */
pthread_mutex_unlock(&first_mutex);
pthread_mutex_unlock(&second_mutex); pthread_mutex_unlock(&second_mutex);
pthread_mutex_unlock(&first_mutex);
pthread_exit(0); pthread_exit(0);
} }
◆ Ti requests instance of Rj Ti
Rj
◆ Ti is holding an instance of Rj Ti
Rj
T1 T2 T3
T1 T2 T3
T2
T3
T1
T4
◆ Allow the system to enter a deadlocked state, detect it, and recover
➢ Deadlock detection
detection
➢ Recovery
Recovery from Deadlock
/* thread one runs in this function */ /* thread two runs in this function */
void *do_work_one(void *param) void *do_work_two(void *param)
{ {
pthread_mutex_lock(&first_mutex); pthread_mutex_lock(&second_mutex);
pthread_mutex_lock(&second_mutex); pthread_mutex_lock(&first_mutex);
/* /*
* Do some work * Do some work
*/ */
pthread_mutex_unlock(&second_mutex); pthread_mutex_unlock(&first_mutex);
pthread_mutex_unlock(&first_mutex); pthread_mutex_unlock(&second_mutex);
pthread_exit(0); pthread_exit(0);
} }
◆ Simplest and most useful model requires that each thread declare
the maximum number of resources of each type that it may need
◆ The deadlock-avoidance algorithm dynamically examines the
resource-allocation state to ensure that there can never be a
circular-wait condition
◆ Resource-allocation state is defined by the number of available
and allocated resources, and the maximum demands of the threads
T1 T2 T1 T2
unsafe state
4. If Finish [i] == true for all i, then the system is in a safe state
◆ The system is in a safe state since the sequence < T1, T3, T4, T2, T0>
satisfies safety criteria
◆ The sequence < T1, T3, T4, T0, T2> is also possible!
◆ Executing safety algorithm shows that sequence < T1, T3, T4, T0, T2>
satisfies safety requirement ==> grant request of T1
◆ Can request for (3,3,0) by T4 be granted? Nope
◆ Can request for (0,2,0) by T0 be granted? Next page!
◆ Detection algorithm
◆ Recovery scheme
T5
T1 T2 T3
T1 T2 T3
T4
T4
◆ Sequence <T0, T2, T3, T1, T4> will result in Finish[i] = true for all i
➔ not in a deadlocked state
◆ State of system?
➢ Can reclaim resources held by process T0, but insufficient resources to
fulfill other processes; requests
➢ Deadlock exists, consisting of processes T1, T2, T3, and T4
◆ Resource Preemption
◆ Rollback – return to some safe state, restart process for that state