ch08 Deadlocks

Download as pdf or txt
Download as pdf or txt
You are on page 1of 47

본 강의 자료는 Wiley 출판사에서 저작한 것을 강의용으로 수정 편집한 것이고, 본 영상은

명지대학교 데이터테크놀로지 전공 강의용으로 제작되었습니다. 본 강의 자료 및 영상의 무단


복제 및 배포는 저작권법에 위배되어 해당 법령에 의해 처벌될 수 있음을 유의 바랍니다.

Chapter 8

Deadlocks

Operating System Concepts


Tenth Edition
Silberschatz, Galvin and Gagne
Chapter 8: Deadlocks

◆ System Model
◆ Deadlock in Multithreaded Applications
◆ Deadlock Characterization
◆ Methods for Handling Deadlocks
◆ Deadlock Prevention
◆ Deadlock Avoidance
◆ Deadlock Detection
◆ Recovery from Deadlock

Copyright © 2020 John Wiley & Sons, Inc. 2


Objectives
◆ Illustrate how deadlock can occur when mutex locks are used
◆ Define the four necessary conditions that characterize deadlock
◆ Identify a deadlock situation in a resource allocation graph
◆ Evaluate the four different approaches for preventing deadlocks
◆ Apply the banker's algorithm for deadlock avoidance
◆ Apply the deadlock detection algorithm
◆ Evaluate approaches for recovering from deadlock

Copyright © 2020 John Wiley & Sons, Inc. 3


4
System Model
◆ System consists of a finite number of resources
◆ Resource types(classes) R1, R2, . . ., Rm
➢ CPU cycles, files, memory space, I/O devices(network interface,
DVD drives)
◆ Each resource type Ri has Wi instances.
➢ e.g. 4 CPUs in a system ➔ resource type CPU has 4 instances
➢ e.g. each instances of a lock ➔ its own resource class
◆ A thread utilizes a resource as follows:
➢ request
➢ use
➢ release
◆ request & release may be system calls

Copyright © 2020 John Wiley & Sons, Inc. 5


Deadlock with Multithreaded Applications
◆ Deadlocks can occur via system calls, locking, etc.
◆ Example: a multithreaded program using POSIX mutex locks
➢ Deadlock may or may not be occurred
➢ Deadlock is possible but not always happening

/* 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);
} }

Copyright © 2020 John Wiley & Sons, Inc. 6


Livelock
◆ Deadlock
Deadlock occurs when every thread in a set of threads is
waiting for an event that can be caused only by another
thread in the set
◆ Livelock
Livelock occurs when threads retry failing operations at the
same time

Copyright © 2020 John Wiley & Sons, Inc. 7


Copyright © 2020 John Wiley & Sons, Inc. 8
Deadlock Characterization
◆ Deadlock can arise if four conditions hold simultaneously.
◆ Mutual
Mutualexclusion:
exclusion only one thread at a time can use a resource
◆ Hold
Holdand wait: a thread holding at least one resource is waiting to
and wait
acquire additional resources held by other threads
◆ NoNopreemption:
preemption a resource can be released only voluntarily by the
thread holding it, after that thread has completed its task
◆ Circular wait: there exists a set {T0, T1, …, Tn} of waiting threads
Circular wait
such that T0 is waiting for a resource that is held by T1, T1 is waiting
for a resource that is held by T2, …, Tn–1 is waiting for a resource that
is held by Tn, and Tn is waiting for a resource that is held by T0.

Copyright © 2020 John Wiley & Sons, Inc. 9


Resource-Allocation Graph 1
◆ A set of vertices V and a set of edges E.
◆ V is partitioned into two types:
➢ T = {T1, T2, …, Tn}, the set consisting of all the active threads in the
system
➢ R = {R1, R2, …, Rm}, the set consisting of all resource types in the
system

◆ request edge – directed edge Ti → Rj


◆ assignment edge – directed edge Rj → Ti

Copyright © 2020 John Wiley & Sons, Inc. 10


Resource-Allocation Graph 2
◆ Thread

◆ Resource Type with 3 instances

◆ Ti requests instance of Rj Ti
Rj

◆ Ti is holding an instance of Rj Ti
Rj

Copyright © 2020 John Wiley & Sons, Inc. 11


Resource-Allocation Graph with a Deadlock

◆ The multithreaded program using POSIX mutex locks

Copyright © 2020 John Wiley & Sons, Inc. 12


Example of a Resource-Allocation Graph

T1 T2 T3

Copyright © 2020 John Wiley & Sons, Inc. 13


Resource-Allocation Graph with A Deadlock

T1 T2 T3

Copyright © 2020 John Wiley & Sons, Inc. 14


Graph With A Cycle But No Deadlock

T2

T3

T1

T4

Copyright © 2020 John Wiley & Sons, Inc. 15


Basic Facts
◆ If graph contains no cycles ➔ no deadlock
◆ If graph contains a cycle ➔
➢ if only one instance per resource type, then deadlock
➢ if several instances per resource type, possibility of deadlock

Copyright © 2020 John Wiley & Sons, Inc. 16


Methods for Handling Deadlocks
◆ Ignore the problem and pretend that deadlocks never occur in the
system
➢ used by most operating systems, including Linux & Windows because
deadlocks occur infrequently and handling deadlocks is expensive
◆ Ensure that the system will never enter a deadlock state:
➢ Deadlock prevention
prevention
➢ Deadlock avoidance
avoidance

◆ Allow the system to enter a deadlocked state, detect it, and recover
➢ Deadlock detection
detection
➢ Recovery
Recovery from Deadlock

Copyright © 2020 John Wiley & Sons, Inc. 17


Deadlock Prevention 1
◆ Ensure that at least one of four necessary conditions for a deadlock
cannot hold

◆ Mutual Exclusion – not required for sharable resources (e.g., read-


only files); but must hold for non-sharable resources(e.g. mutex lock)

◆ Hold and Wait – must guarantee that whenever a thread requests a


resource, it does not hold any other resources
➢ Method 1 - Require each thread to request and be allocated all its
resources before it begins execution
➢ Method 2 - Allow a thread to request resources only when the thread
has none allocated to it.
➢ Low resource utilization; starvation possible

Copyright © 2020 John Wiley & Sons, Inc. 18


Deadlock Prevention 2
◆ No Preemption –
➢ If a thread holding some resources requests another resource that
cannot be immediately allocated to it, then all resources currently being
held are released. Preempted resources are added to resources for
which the thread is waiting.
➢ If a thread requests some resources, first check whether they are
available. If not, check whether they are allocated to some other thread
is waiting for additional resources. Preempt the desired resources from
waiting thread and allocate them to the requesting thread.

◆ Circular Wait – impose a total ordering of all resource types, and


require that each process requests resources in an increasing order
of enumeration

Copyright © 2020 John Wiley & Sons, Inc. 19


Deadlock Prevention 3
◆ Circular wait (cont.): break with lock ordering
➢ All requests for synchronization objects must be made in increasing
order.

➢ thread_two could not request the locks out of order

/* 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);
} }

Copyright © 2020 John Wiley & Sons, Inc. 20


Deadlock Example with Lock Ordering
◆ Lock ordering does not guarantee deadlock prevention if locks can
be acquired dynamically
◆ Example:
➢ thread 1: transaction( A_account, B_account, 25.0 )
➢ thread 2: transaction( B_account, A_account, 50.0 )

void transaction(Account from, Account to, double amount)


{
mutex lock1, lock2;
lock1 = get_lock(from); Transactions 1 and 2 execute concurrently.
lock2 = get_lock(to);
Transaction 1 transfers $25 from account A to B,
acquire(lock1); Transaction 2 transfers $50 from account B to A.
acquire(lock2);
withdraw(from, amount);
deposit(to, amount);
release(lock2);
release(lock1);
}

Copyright © 2020 John Wiley & Sons, Inc. 21


Deadlock Avoidance
◆ Requires that the system has some additional a priori information
available

◆ 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

Copyright © 2020 John Wiley & Sons, Inc. 22


Safe State
◆ When a thread requests an available resource, system must decide
if immediate allocation leaves the system in a safe state
◆ System is in safe state if there exists a sequence <T1, T2, …, Tn> of
safe state
ALL the threads in the systems such that for each Ti, the resources
that Ti can still request can be satisfied by currently available
resources + resources held by all the Tj, with j < i
◆ That is:
➢ If Ti resource needs are not immediately available, then Ti can wait until
all Tj have finished
➢ When Tj is finished, Ti can obtain needed resources, execute, return
allocated resources, and terminate
➢ When Ti terminates, Ti +1 can obtain its needed resources, and so on

Copyright © 2020 John Wiley & Sons, Inc. 23


Safe, Unsafe, Deadlock State

◆ If a system is in safe state


➔ no deadlocks

◆ If a system is in unsafe state


➔ possibility of deadlock

◆ Avoidance ➔ ensure that a


system will never enter an
unsafe state.

Copyright © 2020 John Wiley & Sons, Inc. 24


Avoidance Algorithms
◆ Single instance of a resource type
➢ Use a resource-allocation graph
resource-allocation graph

◆ Multiple instances of a resource type


➢ Use the banker’s
bankersalgorithm
algorithm

Copyright © 2020 John Wiley & Sons, Inc. 25


Resource-Allocation Graph Scheme
◆ Claim edge Ti → Rj indicated that thread Ti may request resource Rj
in the future; represented by a dashed line
◆ Claim edge converts to request edge when a thread requests a
resource
◆ Request edge converted to an assignment edge when the resource
is allocated to the thread
◆ When a resource is released by a thread, assignment edge
reconverts to a claim edge
◆ Resources must be claimed a priori in the system

Copyright © 2020 John Wiley & Sons, Inc. 26


Resource-Allocation Graph Algorithm
◆ Suppose that thread Ti requests a resource Rj
◆ The request can be granted only if converting the request edge to
an assignment edge does not result in the formation of a cycle in the
resource allocation graph
◆ Suppose T2 requests R2. Can allocate R2 to T2 ?

T1 T2 T1 T2

unsafe state

Copyright © 2020 John Wiley & Sons, Inc. 27


Banker’s Algorithm
◆ Multiple instances of each resource type
◆ Each thread must a priori claim maximum use
◆ Data Structures
➢ Let n = number of threads, and m = number of resources types

➢ Available: Vector of length m. If available [j] = k, there are k instances


of resource type Rj available
➢ Max: n x m matrix. If Max [i,j] = k, then thread Ti may request at most k
instances of resource type Rj
➢ Allocation: n x m matrix. If Allocation[i,j] = k then Ti is currently
allocated k instances of Rj
➢ Need: n x m matrix. If Need[i,j] = k, then Ti may need k more instances
of Rj to complete its task

Need [i,j] = Max[i,j] – Allocation [i,j]

Copyright © 2020 John Wiley & Sons, Inc. 28


Resource-Request Algorithm for thread Ti
◆ Requesti = request vector for thread Ti. If Requesti [j] = k then
thread Ti wants k instances of resource type Rj
1. If Requesti  Needi go to step 2. Otherwise, raise error condition,
since thread has exceeded its maximum claim
2. If Requesti  Available, go to step 3. Otherwise Ti must wait,
since resources are not available
3. Pretend to allocate requested resources to Ti by modifying the
state as follows:
Available = Available – Requesti;
Allocationi = Allocationi + Requesti;
Needi = Needi – Requesti;

➢ If safe ➔ the resources are allocated to Ti


➢ If unsafe ➔ Ti must wait, and the old resource-allocation state is
restored

Copyright © 2020 John Wiley & Sons, Inc. 29


Safety Algorithm
1. Let Work and Finish be vectors of length m and n, respectively.
Initialize:
Work = Available
Finish [i] = false for i = 0, 1, …, n-1

2. Find an i such that both:


(a) Finish [i] = false
(b) Needi  Work
If no such i exists, go to step 4

3. Work = Work + Allocationi


Finish[i] = true
go to step 2

4. If Finish [i] == true for all i, then the system is in a safe state

Copyright © 2020 John Wiley & Sons, Inc. 30


Example of Banker’s Algorithm 1
◆ 5 threads T0 through T4
◆ 3 resource types:
A (10 instances), B (5instances), and C (7 instances)
◆ Current state of the system:

Allocation Max Available


ABC ABC ABC
T0 010 753 332
T1 200 322
T2 302 902
T3 211 222
T4 002 433

Copyright © 2020 John Wiley & Sons, Inc. 31


Example of Banker’s Algorithm 2
◆ The content of the matrix Need is defined to be Max – Allocation

Allocation Need Work


ABC
ABC ABC 332
T0 010 743 TT1
1 553322
T1 200 122 TT3
3 774433
T2 302 600 TT4
4 774455
T3 211 011 TT2
2 1010
4747
T4 002 431 TT0
0 1010
5757

◆ 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!

Copyright © 2020 John Wiley & Sons, Inc. 32


Example: T1 Request1(1,0,2)
◆ Check that Request1  Available (that is, (1,0,2)  (3,3,2) ➔ true)
Work
Allocation Need Work ABC
ABC ABC ABC 230
T0 010 743 23 33 202
3 TT1
1 553322
T1 32 0 0
2 010 22 2
00 TT3
3 774433
T2 302 600 TT4
4 774455
T3 211 011 TT0
0 775555
T4 002 431 TT2
2 10105 57 7

◆ 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!

Copyright © 2020 John Wiley & Sons, Inc. 33


Example: T0 Request0 (0,2,0)
◆ Check that Request0  Available (that is, (0,2,0)  (2,3,0) ➔ true)

Allocation Need Work Work


ABC ABC ABC ABC
T0 13 0
00 3 42 3
77 2 31 00
22 1 210
T1 302 020
T2 302 600
T3 211 011
T4 002 431

◆ There is no Needi that is less than or equal to Work!


◆ Unsafe condition! ➔ cannot be granted.

Copyright © 2020 John Wiley & Sons, Inc. 34


Deadlock Detection

◆ Allow system to enter deadlock state

◆ Detection algorithm

◆ Recovery scheme

Copyright © 2020 John Wiley & Sons, Inc. 35


Single Instance of Each Resource Type
◆ Maintain wait-for graph
➢ Resource nodes are removed from resource-allocation graph
➢ Nodes are threads
➢ Ti → Tj if Ti is waiting for Tj

◆ Periodically invoke an algorithm that searches for a cycle in the


graph. If there is a cycle, there exists a deadlock

◆ An algorithm to detect a cycle in a graph requires an order of n2


operations, where n is the number of vertices in the graph

Copyright © 2020 John Wiley & Sons, Inc. 36


Resource-Allocation Graph & Wait-for Graph
T5

T5

T1 T2 T3
T1 T2 T3

T4
T4

Resource-Allocation Graph Corresponding wait-for graph

Copyright © 2020 John Wiley & Sons, Inc. 37


Several Instances of a Resource Type
◆ Available: A vector of length m indicates the number of available
resources of each type
◆ Allocation: An n x m matrix defines the number of resources of
each type currently allocated to each thread
◆ Request: An n x m matrix indicates the current request of each
thread. If Request [i][j] = k, then thread Ti is requesting k more
instances of resource type Rj.

Copyright © 2020 John Wiley & Sons, Inc. 38


Detection Algorithm
1. Let Work and Finish be 3. Work = Work + Allocationi
vectors of length m and n, Finish[i] = true
respectively Initialize: go to step 2
(a) Work = Available
4. If Finish[i] == false,
(b) For I = 1,2, …, n,
for some i, 1  i  n,
if Allocationi  0,
then Finish[i] = false; then the system is in deadlock
state.
otherwise, Finish[i] = true
Moreover, if Finish[i] == false,
then Ti is deadlocked
2. Find an index i such that both:
(a) Finish[i] == false
Algorithm requires an order of
(b) Requesti  Work
O(m x n2) operations to detect
whether the system is in
If no such i exists, go to step 4
deadlocked state

Copyright © 2020 John Wiley & Sons, Inc. 39


Example of Detection Algorithm 1
◆ 5 threads T0 through T4;
◆ 3 resource types: A (7 instances), B (2 instances), and C (6 instances)
◆ Current state of the system:
Work
Allocation Request Available ABC
ABC ABC ABC 000
T0 010 000 000 T0T0 001100
T1 200 202 T2T2 331133
T2 303 000 T3T3 552244
T3 211 100 T1T1 772244
T4 002 002 T4T4 772266

◆ Sequence <T0, T2, T3, T1, T4> will result in Finish[i] = true for all i
➔ not in a deadlocked state

Copyright © 2020 John Wiley & Sons, Inc. 40


Example of Detection Algorithm 2
◆ T2 requests an additional instance of type C

Allocation Request Available Work


ABC ABC ABC
T0 010 000 000 000
T1 200 202 T0 010
T2 303 001
T3 211 100
T4 002 002

◆ 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

Copyright © 2020 John Wiley & Sons, Inc. 41


Detection-Algorithm Usage
◆ When, and how often, to invoke depends on:
➢ How often a deadlock is likely to occur?
➢ How many threads will need to be affected by deadlock when it
happens?

◆ If detection algorithm is invoked arbitrarily, there may be many


cycles in the resource graph and so we would not be able to tell
which of the many deadlocked threads “caused” the deadlock.

Copyright © 2020 John Wiley & Sons, Inc. 42


Recovery from Deadlock

◆ Process and Thread Termination

◆ Resource Preemption

Copyright © 2020 John Wiley & Sons, Inc. 43


Process and Thread Termination
◆ Abort all deadlocked processes

◆ Abort one process at a time until the deadlock cycle is eliminated


➢ Many factors may affect which process is chosen,
1. Priority of the process
2. How long process has computed, and how much longer to
completion
3. Resources the process has used
4. Resources process needs to complete
5. How many processes will need to be terminated

Copyright © 2020 John Wiley & Sons, Inc. 44


Resource Preemption
◆ Successively preempt some resources from processes and give
these resources to other processes until deadlock cycle is broken.

◆ Selecting a victim – minimize cost

◆ Rollback – return to some safe state, restart process for that state

◆ Starvation – same process may always be picked as victim,


include number of rollback in cost factor

Copyright © 2020 John Wiley & Sons, Inc. 45


Summary
Summary

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy