Deadlock
Deadlock
1. Suppose a program has three threads Thread1, Thread2 and Thread3, and a shared
counter variable, count, as shown below:
int count = 10;
Semaphore Lock = 1; // initial value is 1
What are the possible outputs of this program? If there is more than one answer,
provide them all. Some of the following arrangements of Threads, and the locks that
they will grab, can lead to deadlock. Which ones? Why?
Available
RA RB RC RD
8 5 9 7
Maximum Demand
RA RB RC RD
P0 3 2 1 4
P1 0 2 5 2
P2 5 1 0 5
P3 1 5 3 0
P4 3 0 3 3
Current Allocation
RA RB RC RD
P0 1 0 1 1
P1 0 1 2 1
P2 4 0 0 3
P3 1 2 1 0
P4 1 0 3 0
3. Consider the directed resource graph given below. (R1-2 means Resource 1 has 2 units of
non-sharable resource.)
a. Is this system, as a whole, deadlocked?
b. Are there any deadlocked processes?
c. Three processes are requesting resources from R2.
i. Which requests would you satisfy to minimize the number of processes
involved in the deadlock?
ii. Which requests would you satisfy to maximize the number of
processes involved in deadlock?
R1-2 R2-2
R3-1 R4 -1
4. For the three systems described in I – III below, given that all of the devices are of the
same type, consider applying Banker’s Algorithm to answer these questions:
a. Determine the remaining needs for each job in each system.
b. Determine whether each system is safe or unsafe.
c. If the system is in a safe state, list the sequence of requests and releases that
will make it possible for all processes to run to completion.
d. If the system is in an unsafe state, show how it’s possible for deadlock to
occur.
6. A system has 4 processes and 5 allocatable resources. The current allocation and
maximum needs tables and available vector are as follows:
7. A computer has six tape drives, with 'n' processes competing for them. Each process may
need 2 drives. For what value(s) of 'n' is the system deadlock free.
8. Consider a system has p processes. Each process need a maximum of m resources and a
total of r resources available. What condition must hold to make the system deadlock
free?
9. Can a system be in a state that is neither deadlocked nor safe? If so, give an example.
If not, prove that all states are either deadlocked or safe.
11.
12. What is wait-for graph? Under what conditions can we use the Wait-for graph to detect
deadlock? Consider the following resource allocation graph. Draw the wait-for graph and
detect whether the system is deadlocked or not.
13. Cinderella and the Prince are getting divorced. To divide their property, they have agreed
on the following algorithm. Every morning, each one may send a letter to the other's
lawyer requesting one item of property. Since it takes a day for letters to be delivered,
they have agreed that if both discover that they have requested the same item on the same
day, the next day they will send a letter canceling the request. Among their property is
their dog, Woofer, Woofer's doghouse, their canary, Tweeter, and Tweeter's cage. The
animals love their houses, so it has been agreed that any division of property separating
an animal from its house is invalid, requiring the whole division to start over from
scratch. Both Cinderalla and the Prince desperately want Woofer. So they can go on
separate vacations, each spouse has programmed a personal computer to handle the
negotiation. When they come back from vacation, the computers are still negotiating.
Why? Is deadlock possible? Is starvation possible? Discuss.
14. Consider the following snapshot of a system with five processes (p1, ... p5) and four
resources (r1, ... r4). There are no current outstanding queued unsatisfied requests.
a. Compute what each process still might request and fill in the “still needs” columns.
b. Is this system currently deadlocked, or will any process become deadlocked? Why
or why not? If not, give an execution order.
c. If a request from p3 arrives for (0, 1, 0, 0), can that request be safely granted
immediately? In what state deadlocked, safe, unsafe) would immediately granting the
whole request leave the system? Which processes, if any, are or may become
deadlocked if this whole request is granted immediately?
15. Explain Bankers algorithm? Solve the given problem using the same:
Allocation MAX
A B C D
P0 0 0 1 2
P0 0 0 1 2
P1 1 0 0 0
P1 1 7 5 0
P2 1 3 5 4
P2 2 3 5 6
P3 0 6 3 2
P3 0 6 5 2
P4 0 0 1 4
P4 0 6 5 6
AVAILABLE
A=1, B=5, C=2, D=0
16. For the following set of the process find the avg waiting time and avg turn around turn
using GANTT chart for a) FCFS b) SJF( primitive and nonprimitive)
Process Arrival time Burst time
P1 0 4
P2 1 2
P3 2 5
P4 3 4
Write code to synchronize the student threads and the pizza delivery thread. Your
solution should avoid deadlock and phone Satisfactions (i.e., wake up the delivery
thread) exactly once each time a pizza is exhausted. No piece of pizza may be
consumed by more than one student.
19. Flipping Philosophers. The Dining Philosophers have worked up a solution to avoid
deadlock, with a little help from a consultant with a recent doctorate in algorithms.
Before eating, each philosopher will flip a coin to decide whether to pick up the left fork
or the right fork first. If the second fork is taken, the philosopher will put the first fork
down, then flip the coin again. Is this solution deadlock-free? Does it guarantee that
philosophers will not starve? Modify the solution as necessary to guarantee freedom
from deadlock and starvation.
20. Expensive Candy. Three engineering professors have gone to the faculty club to eat
licorice. Each piece of licorice costs 36 cents. To buy a piece of licorice, a professor
needs a quarter, a dime, and a penny (they do not give change, and they don’t take
American Express). The first professor has a pocket full of pennies, the second a supply
of quarters, and the third a supply of dimes. A wealthy alum walks up to the bar and lays
down at random two of the three coins needed for a piece of licorice. The professor with
the third coin takes the money and buys the licorice. The cycle then repeats. Show how
to synchronize the professors and the alum. [Patil71, Parnas75, Andrews91]
21. Tweedledum and Tweedledee are separate threads executing their respective procedures.
The code below is intended to cause them to forever take turns exchanging insults
through the shared variable X in strict alternation. The Sleep() and Wakeup() routines
operate as discussed in class: Sleep blocks the calling thread, and Wakeup unblocks a
specific thread if that thread is blocked, otherwise its behavior is unpredictable (like
Nachos Scheduler::ReadyToRun).
void void
Tweedledum() Tweedledee()
{ {
while(1) { while(1) {
Sleep(); x = Quarrel(x);
x = Quarrel(x); Wakeup(Tweedledum thread);
Wakeup(Tweedledee thread); Sleep();
} }
} }
23. Trapeze is a locally grown high-speed messaging system for gigabit-per-second Myrinet
networks. When a message arrives, the network interface card (NIC) places it in a FIFO
queue and interrupts the host. If the host does not service the interrupts fast enough then
incoming messages build up in the queue. Most incoming messages are handled by a
special thread in the host (the server thread). However, many Trapeze messages are
replies to synchronous requests (RPCs) issued earlier from the local node; the reply
handler code must execute in the context of the thread that issued the request, which is
sleeping to await the reply. As an optimization, the receiver interrupt handler services
reply messages by simply waking up the requester thread, saving an extra context switch
to the server thread if it is not already running.
Show how to synchronize the receiver interrupt handler and the server thread to
implement the following behavior. On an interrupt, the handler removes messages
from the queue, processing reply messages by waking up waiting threads. If it
encounters a message that is not a reply message then it wakes up the server thread to
process all remaining pending messages (including reply messages). The interrupt
handler completes if it awakens the server thread, or if the FIFO queue is empty. The
server thread simply loops processing messages in order, sleeping whenever the queue
is empty.
24. Highway 110 is a two-lane north-south road that passes through a one-lane tunnel. A car
can safely enter the tunnel if and only if there are no oncoming cars in the tunnel. To
prevent accidents, sensors installed at each end of the tunnel notify a controller computer
when cars arrive or depart the tunnel in either direction The controller uses the sensor
input to control signal lights at either end of the tunnel.
Show how to implement the controller program correctly using mutexes and condition
variables. You may assume that each car is represented by a thread that calls Arrive()
and Depart() functions in the controller, passing an argument indicating the direction
of travel. You may also assume that Arrive() can safely stop the arriving car by
changing the correct signal light to red and blocking the calling thread. Your solution
should correctly handle rush hour, during which most cars approach the tunnel from
the same direction. (Translation: your solution should be free from starvation.)
25. Is the Nachos semaphore implementation fair, e.g., is it free from starvation? How about
the semaphore implementation (using mutexes and condition variables) presented in
class? If not, show how to implement fair semaphores in each case.
26. Round-robin schedulers (e.g., the Nachos scheduler) maintain a ready list or run queue of
all runnable threads (or processes), with each thread listed at most once in the list. What
can happen if a thread is listed twice in the list? Explain how this could cause programs
to break on a uniprocessor. For extra credit: what additional failure cases could occur on
a multiprocessor?
27. A student majoring in anthropology and minoring in computer science has embarked on a
research project to see if African baboons can be taught about deadlocks. He locates a
deep canyon and fastens a rope across it, so the baboons can cross hand-over-hand.
Several baboons can cross at the same time, provided that they are all going in the same
direction. If eastward moving and westward moving baboons ever get onto the rope at
the same time, a deadlock will result (the baboons will get stuck in the middle) because it
is impossible for one baboon to climb over another one while suspended over the canyon.
If a baboon wants to cross the canyon, it must check to see that no other baboon is cur-
rently crossing in the opposite direction. Write a program using semaphores that avoids
deadlock. Do not worry about a series of eastward moving baboons holding up the
westward moving baboons indefinitely.
28. A distributed system using mailboxes has two IPC primitives, send and receive. The lat-
ter primitive specifies a process to receive from, and blocks if no message from that
process is available, even though messages may be waiting from other processes. There
are no shared resources, but processes need to communicate frequently about other
matters. Is deadlock possible? Discuss.
29. The Sleeping Professor Problem. Once class is over, professors like to sleep — except
when students bother them to answer questions. You are to write procedures to
synchronize threads representing one professor and an arbitrary number of students.
A professor with nothing to do calls IdleProf(), which checks to see if a student is
waiting outside the office to ask a question. IdleProf sleeps if there are no students
waiting, otherwise it signals one student to enter the office, and returns. A student
with a question to ask calls ArrivingStudent(), which joins the queue of students
waiting outside the office for a signal from the professor; if no students are waiting,
then the student wakes up the sleeping professor. The idea is that the professor and
exactly one student will return from their respective functions “at the same time”:
after returning they discuss a topic of mutual interest, then the student goes back to
studying and the professor calls IdleProf again.
a) Implement IdleProf and ArrivingStudent using mutexes and condition
variables. You may assume that mutexes and condition variables are fair (e.g.,
FIFO).
b) Implement IdleProf and ArrivingStudent using semaphores. You may
assume that semaphores are fair (e.g., FIFO).
In this problem you are to compare the storage needed to keep track of free memory
using a bitmap versus using a linked list. The 128-MB memory is allocated in units
of n bytes. For the linked list, assume that memory consists of an alternating
sequence of segments and holes, each 64KB. Also assume that each node in the
linked list needs a 32-bit memory address, a 16-bit length, and a 16-bit next node
field. How many bytes of storage are required for each method? Which one is better?
30. Students working at individual PCs in a computer laboratory send
their files to be printed by a server that spools the files on its hard
disk. Under what conditions may a deadlock occur if the disk space
for the print spool is limited? How may the deadlock be avoided?
Which resources are preemptable and which are nonpreemptable
31. The four conditions (mutual exclusion, hold and wait, no preemption
and circular wait) are necessary for a resource deadlock to occur.
Give an example to show that these conditions are not sufficient for
a resource deadlock to occur. When are these conditions sufficient
for a resource deadock to occur?
32. City streets are vulnerable to a circular blocking condition called
gridlock, in which intersections are blocked by cars that then block
cars behind them that then block the cars that are trying to enter
the previous intersection, etc. All intersections around a city block
are filled with vehicles that block the oncoming traffic in a circular
manner. Gridlock is a resource deadlock and a problem in
competition synchronization. New York City’s prevention algorithm,
called "don’t block the box," prohibits cars from entering an
intersection unless the space following the intersection is also
available. Which prevention algorithm is this? Can you provide any
other prevention algorithms for gridlock?
33. Suppose four cars each approach an intersection from four different
directions simultaneously. Each corner of the intersection has a stop
sign. Assume that traffic regulations require that when two cars
approach adjacent stop signs at the same time, the car on the left
must yield to the car on the right. Thus, as four cars each drive up
to their individual stop signs, each waits (indefinitely) for the car on
the left to proceed. Is this anomaly a communication deadlock? Is it
a resource deadlock?
36. In order to control traffic, a network router, A periodically sends a message to its
neighbor, B, telling it to increase or decrease the number of packets that it can handle.
At some point in time, Router A is flooded with traffic and sends B a message telling
it to cease sending traffic. It does this by specifying that the number of bytes B may
send (A’s window size) is 0. As traffic surges decrease, A sends a new message,
telling B to restart transmission. It does this by increasing the window size from 0 to a
positive number. That message is lost. As described, neither side will ever transmit.
What type of deadlock is this?
38. A system has two processes and three identical resources. Each process needs a
maximum of two resources. Is deadlock possible? Explain your answer. Consider the
previous problem again, but now with p processes each needing a maximum of m
resources and a total of r resources available. What condition must hold to make the
system deadlock free?
39. In an electronic funds transfer system, there are hundreds of identical processes that
work as follows. Each process reads an input line specifying an amount of money, the
account to be credited, and the account to be debited. Then it locks both accounts and
transfers the money, releasing the locks when done. With many processes running in
parallel, there is a very real danger that a process having locked account x will be
unable to lock y because y has been locked by a process now waiting for x. Devise a
scheme that avoids deadlocks. Do not release an account record until you have
completed the transactions. (In other words, solutions that lock one account and then
release it immediately if the other is locked are not allowed.)
43.
Compare this set of definitions with that of Figure 5.3 . Note one difference: With
the preceding definition, a semaphore can never take on a negative value. Is there
any difference in the effect of the two sets of definitions when used in programs?
That is, could you substitute one set for the other without altering the meaning of the
program?
44. Five silent philosophers sit at a round table with bowls of spaghetti. Forks are placed
between each pair of adjacent philosophers. Each philosopher must alternately think
and eat. However, a philosopher can only eat spaghetti when he has both left and right
forks. Each fork can be held by only one philosopher and so a philosopher can use the
fork only if it is not being used by another philosopher. After he finishes eating, he
needs to put down both forks so they become available to others. Now suppose there
are two types of dining philosophers. One type always picks up his left fork first and
the other type always picks up his right fork first - call these a lefty and a righty. Each
type executes consecutive “wait”s on their forks (left followed by right for lefties, and
the other way around for righties), eats, then put down the forks in the reverse order of
the waits(right followed by left for lefties, and the other way around for the
righties).Explain why every seating arrangement of lefties and righties, with at least
one of each, avoids deadlock.
45. Suppose there are 2 copies of resource A, 3 copies of resource B, and 3 copies of
resource C. Suppose further that process 1 holds one unit of resources B and C and is
waiting for a unit of A; that process 2 is holding a unit of A and waiting on a unit of
B; and that process 3 is holding one unit of A, two units of B, and one unit of C.
Draw the resource allocation graph. Is the system in a deadlocked state? Why or why
not?
46. Consider the following system snapshot using data structures in the Banker’s
algorithm, with resources A, B, C, and D, and process P0 to P4:
47. Consider a system with four processes P1, P2, P3, and P4, and two resources, R1,
and R2, respectively.
Each resource has two instances. Furthermore:
P1 allocates an instance of R2, and requests an instance of R1.
P2 allocates an instance of R1, and doesn’t need any other resource.
P3 allocates an instance of R1 and requires an instance of R2.
P4 allocates an instance of R2, and doesn’t need any other resource
Draw the resource allocation graph.
Is there a cycle in the graph? If yes name it.
Is the system in deadlock? If yes, explain why. If not, give a possible sequence of
executions after which every process completes.