0% found this document useful (0 votes)
45 views

Deadlock

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
45 views

Deadlock

Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 15

Deadlock - synchronization

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

Thread1 Thread2 Thread3


// do something // do something // do something
wait(Lock); wait(Lock); wait(Lock);
count++; count−−; printf(“%d”, count);
Signal(Lock); Signal(Lock); Signal(Lock);

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?

Case I: Thread 1: will try to grab locks 1 and 2 in an arbitrary order.


Thread 2: will try to grab locks 1 and 2 in fixed order, 1 then 2
Case II: Thread 1: will try to grab locks 1 and 2 in fixed order, 1 then 2.
Thread 2: will try to grab locks 1 and 2 in fixed order, 2 then 1
Case III: Thread 1: will try to grab locks 1 and 2 in fixed order, 1 then 2
Thread 2: will try to grab locks 1, 2 and 3 in fixed order, 1 then 2 then 3.
Case IV Thread 1: will try to grab locks 1 and 2 in an arbitrary order.
Thread 2: will try to grab locks 2 and 3 in an arbitrary order.
Thread 3: will try to grab locks 1.

2. Consider the following snapshot of a system (P=Process, R=Resource) :

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

Answer the following questions using banker’s algorithm:


 Calculate the Needs matrix:
 Is the system in a safe state? If so, show a safe order in which the
processes can run.
 Can a request of one instance of RA by Process P0 be granted safely
according to Banker’s algorithm?

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.

I. System I has 12 devices; only 1 is available.

Job No. Devices Allocated Maximum Required Remaining Needs


1 5 6
2 4 7
3 2 6
4 0 2

II. System II has 14 devices; only 2 are available.


Job No. Devices Allocated Maximum Required Remaining Needs
1 5 8
2 3 9
3 4 8

III. System III has 12 devices; only 2 are available.


Job No. Devices Allocated Maximum Required Remaining Needs
1 5 8
2 4 6
3 1 4

5. This refers to a single resource (may think of it as money in thousands).


Has Max
P0 1 6
P1 1 5
P2 2 4
P3 4 7
FREE: 2
If P3 asks for 1 more, does this lead to a safe or unsafe state? Why?
If instead, P2 asks for 1 more, does this lead to a safe or unsafe state? Why?

6. A system has 4 processes and 5 allocatable resources. The current allocation and
maximum needs tables and available vector are as follows:

Allocated Maximum Available


P0 10211 11213 00X11
P1 20110 22210
P2 11010 21310
P3 11110 11221

What is the smallest value of X for which this is a safe state?

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.

10. Consider a system with four resource types as follows:


Resource Type Number of Instances
a. RT1 6
b. RT2 9
c. RT3 12
d. RT4 5
The following table presents the maximum resource needs for each process for each
of the four resource types:
Process Max RT1 Need Max RT2 Need Max RT3 Need Max RT4 Need
P1 5 6 8 4
P2 3 7 4 3
P3 4 5 7 2
In the following sequence of resource requests, let REQ(A, N1, N2, N3, N4) represent
a request from process A for N1 resources of type RT1, N2 resources of type RT2, N3
resources of type RT3 and N4 resources of type RT4:
• REQ(P1, 0, 1, 3, 0)
• REQ(P3, 3, 0, 3, 0)
• REQ(P1, 0, 1, 0, 1)
• REQ(P2, 0, 1, 0, 0)
• REQ(P3, 0, 3, 1, 0)
• REQ(P2, 1, 0, 0, 1)
The above sequence of resource requests can be granted safely without any danger of
leading the system into a deadlock situation. Determine the set of resources available
after processing the above sequence of requests and the remaining resource needs of
the processes. Verify that a safe sequence of resource allocation to the processes does
exist in this situation.
Now, consider the following additional requests for resources. For each request,
determine if it can be granted safely in a manner that avoids deadlocks. Identify the
request that can be safely granted.
a) REQ(P1, 1, 0, 2, 0) d) REQ(P1, 0, 0, 2, 1)
b) REQ(P2, 0, 1, 0, 2) e) REQ(P2, 0, 2, 1, 0)
c) REQ(P2, 0, 1, 3, 0) f) REQ(P2, 0, 2, 2, 0)

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.

currently available resources


r1 r2 r3 r4
2 1 0 0

current allocation max demand still needs


Process r1 r2 r3 r4 r1 r2 r3 r4 r1 r2 r3 r4
p1 0 0 1 2 0 0 1 2
p2 2 0 0 0 2 7 5 0
p3 0 0 3 4 6 6 5 6
p4 2 3 5 4 4 3 5 6
p5 0 3 3 2 0 6 5 2

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

o what is the content of the need matrix


o Is the system in a safe state?
o If P1 request for the (0,4,2,0) can the request be granted immediately?

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

17. Consider the following system having below status:


Process Arrival time Burst time
P1 10 3
P2 1 1
P3 2 3
P4 1 4
P5 5 2
a) Draw four GANTT charts for FCFS ,SJF, priority and RR( Quantum =1)
b) What is a turn around time for each of the scheduling algorithm
c) What is the waiting time of each of the scheduling algorithm
d) Which of the schedule gives the minimum avg waiting time?
18. Late-Night Pizza. A group of students are studying for a CPS 110 exam. The students
can study only while eating pizza. Each student executes the following loop: while (true)
{ pick up a piece of pizza; study while eating the pizza}. If a student finds that the pizza is
gone, the student goes to sleep until another pizza arrives. The first student to discover
that the group is out of pizza phones Satisfactions at Brightleaf to order another pizza
before going to sleep. Each pizza has S slices.

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();
} }
} }

a) The code shown above exhibits a well-known synchronization flaw. Briefly


outline a scenario in which this code would fail, and the outcome of that scenario.
b) Show how to fix the problem by replacing the Sleep and Wakeup calls with
semaphore P (down) and V (up) operations. No, you may not disable interrupts or use
Yield.
c) Implement Tweedledum and Tweedledee correctly using a mutex and condition
variable.
22. Cold coffee. The espresso franchise in the strip mall near my house serves customers
FIFO in the following way. Each customer entering the shop takes a single “ticket” with
a number from a “sequencer” on the counter. The ticket numbers dispensed by the
sequencer are guaranteed to be unique and sequentially increasing. When a barrista is
ready to serve the next customer, it calls out the “eventcount”, the next highest unserved
number previously dispensed by the sequencer. Each customer waits until the eventcount
reaches the number on its ticket. Each barrista waits until the customer with the ticket it
called places an order.
Show how to implement sequencers, tickets, and eventcounts using mutexes and
condition variables. Your solution should also include code for the barrista and
customer threads.

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?

34. Is it possible that a resource deadlock involves multiple units of one


type and a single
unit of another? If so, give an example.

35. Suppose that there is a resource deadlock in a system. Give an


example to show that
the set of processes deadlocked can include processes that are not
in the circular chain
in the corresponding resource allocation graph.

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?

37. In theory, resource trajectory graphs could be used to avoid


deadlocks. By clever
scheduling, the operating system could avoid unsafe regions. Is
there a practical way
of actually doing 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.)

40. A computer science student assigned to work on deadlocks thinks of


the following brilliant way to eliminate deadlocks. When a process
requests a resource, it specifies a time limit. If the process blocks
because the resource is not available, a timer is started. If the time
limit is exceeded, the process is released and allowed to run again.
If you were the professor, what grade would you give this proposal
and why?

41. Consider the following program:

Note that the scheduler in a uniprocessor system would implement pseudo-parallel


execution of these two concurrent processes by interleaving their instructions, without
restriction on the order of the interleaving.
a. Show a sequence (i.e., trace the sequence of interleavings of statements)
such that the statement “x is 10” is printed.
b. Show a sequence such that the statement “x is 8” is printed. You should
remember that the increment/decrements at the source language level are not
done atomically, that is, the assembly language code:
LD R0,X /* load R0 from memory location x */
INCR R0 /* increment R0 */
STO R0,X /* store the incremented value back in X */
implements the single C increment instruction (x = x + 1).

42. Consider the following program:


const int n = 50;
int tally;
void total()
{
int count;
for (count = 1; count<= n; count++){
tally++;
}
}
void main()
{
tally = 0;
parbegin (total (), total () );
write (tally);
}
a. Determine the proper lower bound and upper bound on the final value of the
shared variable tally output by this concurrent program. Assume processes can
execute at any relative speed and that a value can only be incremented after it
has been loaded into a register by a separate machine instruction.
b. Suppose that an arbitrary number of these processes are permitted to execute
in parallel under the assumptions of part (a). What effect will this modification
have on the range of final values of tally ?

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:

Using Banker’s algorithm, answer the following questions.


 How many resources of type A, B, C, and D are there?
 What are the contents of the Need matrix?
 Is the system in a safe state? Why?
 If a request from process P4 arrives for additional resources of (1,2,0,0,), can the
Banker’s algorithm grant the request immediately? Show the new system state and
other criteria.

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.

You might also like