OS Unit - 3 Notes
OS Unit - 3 Notes
OS Unit - 3 Notes
UNIT-III
Deadlocks-System Model, Deadlocks Characterization, Methods for Handling
Deadlocks, Deadlock Prevention, Deadlock Avoidance, Deadlock Detection, and
Recovery from Deadlock .
Process Management and Synchronization-The Critical Section Problem,
Synchronization Hardware, Semaphores, and Classical Problems of
Synchronization, Critical Regions, Monitors, Inter-process Communication
Mechanisms- IPC between processes on a single computer system, IPC between
processes on different systems, using pipes, FIFOs, message queues, shared memory.
I. DEADLOCKS
1. SYSTEM MODEL
• A system can be modeled as a collection of limited resources to be allocated
to number of processes needs to be executed.
• For example, resources may include memory, printers, CPUs, open files, tape
drives, CD-ROMS, etc.
• Some resources may have a single instance and some of them may have
multiple instances.
• In normal operation a process must request a resource before using it, and
release it whenits usage is completed, in the following sequence:
1. Request: Every process must put a request to get the required resource.
If the request cannot be immediately granted, then the process must
wait until the resource(s) it needs become available.
2. Use: The process uses the resource, e.g. prints to the printer or reads from
the file.
3. Release: The process releases the resource when its usage is completed.
So that it becomes available for other processes.
2. DEADLOCKS CHARECTERIZATION
Deadlock Definition: Deadlock is a situation where, the execution of two or more
processesis blocked because each process holds some resource and waits for other
resource held by some other process.
Example:
the resourceheld by the second process, the second process is waiting for the
resource held by the third process, and so on. At last, the last process is waiting
for the resource held by the first process. So, every process is waiting for each
other and forms a circular wait.
Deadlock will occur if all the above four conditions happen simultaneously.
1. Deadlock prevention: In this method, the system will prevent the happening of
at least one of the four necessary conditions of the deadlock.
2. Deadlock avoidance: In this method, the system always wants to be in a safe
state. It maintains a set of data and using that data it decides whether a new
request should be accepted or not. If the system is going into the unsafe state by
taking that new request, then that request is avoided. Otherwise the request is
accepted.
3. Deadlock detection and recovery: The CPU apply periodically Bankers
algorithm or checkfor cycles in resource allocation graph to detect the deadlock.
If deadlock is detected, then the system abort one after the other process or
preempt some resources until the deadlock is gone.
4. Deadlock Ignorance: If deadlocks only occur once a year or so, it may be
better to simplylet them happen and reboot as necessary than to incur the constant
overhead and system performance penalties associated with deadlock prevention
or detection. This is the approach that both Windows and UNIX take.
4. DEADLOCK PREVENTION
The deadlock prevention strategy involves designing a system that violates
one of the four necessary conditions for the occurrence of deadlock. This ensures
that the system remains free from the deadlock. The various conditions to violate
necessary conditions are:
(1). Mutual Exclusion:
• To violate this condition, all the system resources must be shareable.
• But in reality, some resources can not be shared. For example, Printer. It is
mutually exclusive by nature. So, this condition can not be violated always.
(2). Hold and Wait: This condition can be violated in the following ways-
Approach-01: Starts with all approach
• A process has to first request for all the resources it requires for execution.
• Once it has acquired all the resources, only then it can start its execution.
• This approach ensures that the process does not hold some resources and wait
for other resources.
• But this approach is less efficient and cannot be implementable since it is not
possible to predict in advance which resources will be required during
execution.
Approach-02: Start with few and acquire remaining latter approach
• A process is allowed to acquire the resources it desires at the current moment.
• After acquiring the resources, it can start execution.
• Latter, in order to continue the execution, the process may need other
resources. Now before making any new request, it has to compulsorily release
all the resources that it holds currently.
• This approach is efficient and implementable.
Claim edge: When the process Pi needs resource Rj, first process Pi place claim
edge to resource Rj. Latter, the claim edge will be converted into request edge if it
does not form a cycle.
If a process is using (or assigned) a resource, an arrow is drawn from the resource
node to theprocess node.
If a process is requesting a resource, an arrow is drawn from the process node to
the resourcenode.
Syeda Sumaiya Afreen pg.
5
R20 CMR Technical Campus
➢ Resource instances:
• One instance of resource type R1
• Two instances of resource type R2
• One instance of resource type R3
• Three instances of resource type R4
Syeda Sumaiya Afreen pg.
6
R20 CMR Technical Campus
➢ Process states:
• Process P1 is holding an instance of resource type R2 and is waiting for an
instance of resource type R1.
• Process P2 is holding an instance of R1 and an instance of R2 and is waiting for
an instance of R3.
• Process P3 is holding an instance of R3.
Given the definition of a resource-allocation graph, it can be shown that, if the graph
contains no cycles, then no process in the system is deadlocked. If the graph does
contain a cycle, then a deadlock may exist.
If each resource type has exactly one instance, then a cycle implies that a
deadlock has occurred. If the cycle involves only a set of resource types, each of which
has only a single instance, then a deadlock has occurred. Each process involved in the
cycle is deadlocked. In this case, a cycle in the graph is both a necessary and a
sufficient condition for the existence of deadlock.
If each resource type has several instances, then a cycle does not necessarily
imply that a deadlock has occurred. In this case, a cycle in the graph is a necessary but
not a sufficient condition for the existence of deadlock.
To illustrate this concept, we return to the resource-allocation graph depicted in
(Figure 5.1). Suppose that process P3 requests an instance of resource type R2. Since
no resource instance is currently available, a request edge P3 —>R2 is added to the
graph (Figure 5.2). At this point, two minimal cycles exist in the svstem:
Processes P1, P2, and P3 are deadlocked. Process P2 is waiting for the resource R3,
which is held by process P3. Process P3 is waiting for either process P1 or
However, there is no deadlock. Observe that process P4 may release its instance of
resource type R2. That resource can then be allocated to P3, breaking the cycle.
In summary if a resource-allocation graph does not have a cycle, then the system is
not in a deadlocked state. If there is a cycle, then the system may or may not be in a
deadlocked state. This observation is important when we deal with the deadlock
problem.
Example 1 (Single instances RAG): process P1 holds resource R1 and waiting for
R2, process P2 holds resource R2 and waiting for R1. Assume R1 and R2 are single
instance. The RAG is given below
P1
P1 is holding R1 P1 is waiting for R2
R1 R2
P2 P2 is holding R2
P2 is waiting for R1
If there is a cycle in the Resource Allocation Graph and each resource in the
cycle provides only one instance, then the processes will be in deadlock. Therefore
process P1 and process P2 are in deadlock.
Note: RAG can not be used to detect deadlock, if the number of instances of any
resource is greater than one.
6. DEADLOCK AVOIDANCE
Deadlock-prevention algorithms, as discussed earlier, prevent deadlocks
by restraining how requests can be made. The restraints ensure that at least one of
the necessary conditions for deadlock cannot occur and, hence, that deadlocks
cannot hold. Possible side effects of preventing deadlocks by this method,
however, are low device utilization and reduced system throughput.
An alternative method for avoiding deadlocks is to require additional
information about how resources are to be requested. For example, in a system
with one tape drive and one printer, the system might need to know that process P
will request first the tape drive and then the printer before releasing both
Syeda Sumaiya Afreen pg.
9
R20 CMR Technical Campus
resources, whereas process Q will request first the printer and then the tape drive.
With this knowledge of the complete sequence of requests and releases for each
process, the system can decide for each request whether or not the process should
wait in order to avoid a possible future deadlock. Each request requires that in
making this decision the system consider the resources currently available, the
resources currently allocated to each process, and the future requests and releases
of each process.
Safe State
• The general idea behind deadlock avoidance is that it makes sure always
the system is insafe state and will not enter into unsafe state.
• A system is in safe state if there exists a safe sequence of processes { P0,
P1, P2, ..., Pn }such that all of the resource requests for each Pi can be
satisfied by currently available resources + resources held by all other
processes Pj, where j < i in safe sequence.
• If a safe sequence exists, then the system is in not in deadlock.
• If a safe sequence does not exist, then the system is in an unsafe state,
which may lead todeadlock.
• All safe states are deadlock free, but not all unsafe states lead to deadlocks.
unsafe
deadlock
safe
resources)
Suppose that P2requests R2. Although R2 is currently free, we cannot allocate it to P2,
since this action will create a cycle in the graph (Figure 6.2). A cycle indicates that the
system is in an unsafe state. If P1 requests R2, and P2 requests R1, then a deadlock will
occur.
The algorithm for finding out whether or not a system is in a safe state. This algorithm
can be described, as follows:
Step 1: Let Workand Finishbe vectors of length m and n, respectively. ( m is
the totalnumber of resources and n is the total number of processes)
Initially, Work = Available Finish[i]
=falsefor i = 0, 1, ... , n - 1.
Step 2: Find an index i such that both the below conditions satisfies
Finish[i]== false
Needi<= Work
If there is no such i present, then proceed to step 4.
Step 3: Perform the following:
Work = Work + Allocation;Finish[i] =
true;
Go to step 2.
Step 4: If Finish[i] == truefor all i, then the system is in a safe state.
That means if all processes are finished, then the system is in safe state.
Let Requestibe the request array for process Pi. Requesti[j]= kmeans process Pi wants
k instances of resource type Rj. When a request for resources is made by process Pi,
the following actions are taken:
Resource-Request Algorithm
Step 1: If Requesti<= Needi
Goto step (2); otherwise, raise an error condition, since the process has
exceeded itsmaximum claim.
If the resulting resource-allocation state is safe, the transaction is completed, and process
P; is allocated its resources. However, if the new state is unsafe, then P, must wait for
Request , and the old resource-allocation state is restored.
P4 0 0 2 4 3 3
7 5 3 0 1 0
3 2 2 2 0 0
= 9 0 2 - 3 0 2
2 2 2 2 1 1
4 3 3 0 0 2
7 4 3
1 2 2
= 6 0 0
0 1 1
4 3 1
b) Is the system in a safe state? If yes, then what is the safe sequence?
Solution: Use safety algorithm steps to check whether the system is in safe state
or not.
P1 work = [3 3 2 ] + [2 0 0] = [5 3 [F TF F F]
2]
P3 work = [5 3 2 ] + [2 1 1] = [7 4 [F TF T F]
3]
P4 work = [7 4 3 ] + [0 0 2] = [7 4 [F TF T T]
5]
P2 work = [7 4 5 ] + [3 0 2] = [10 4 [ F T T T T]
5]
P0 work = [10 4 5 ] + [0 1 0] = [10 [T TT T T]
5 7]
So, the system is in safe state. As the system is in safe state, there is no
deadlock. The safe sequence is < P1, P3, P4, P2, P0>.
Solution: P1 request for one additional instance of resource type A and two
instances ofresource type C. i.e., P1 request = [ 1 0 2]
The request made by a process should be accepted or not is decided by
applying the steps ofresource-request algorithm.
then go to step 2)
Step
3: Available= Available –Requesti
= [3 3 2 ] – [ 1 0 2 ]
= [2 3 0 ]
Allocationi= Allocationi+ Requesti
= [2 0 0 ] + [ 1 0 2 ]
Syeda Sumaiya Afreen pg.
16
R20 CMR Technical Campus
ti =
[ = [1 2 2 ] – [ 1 0 2 ]
3 = [0 2 0 ]
0
As the resource-request algorithm steps completed, we need to check the safety
algo2rithm for existence of any safe sequence or not. If safe sequence exists, then
only] the changes made by resource-request algorithms become permanent.
Needi Otherwise, its changesare rejected. It means the new request is rejected.
After inserting the modifications done in the above the Allocation, Max, Need
= and Available is
Needi–
Reques
Step 2 & 3:
So, the system is in safe state. As the systemis in safe state, there is no
deadlock. The safe sequence is < P1, P3, P4, P0, P2 >. As there exist a safe
sequence, the request made by P1 is accepted and the changes done by
resource- request algorithm are made permanent.
Solution: P4 request = [ 3 3 0]
The request made by a process should be accepted or not is decided by
applying the steps ofresource-request algorithm.
Step 1: If Requesti<= Needithen go to step 2. Otherwise
Step 3:
Available= Available –Requesti
= [3 3 2 ] – [ 3 3 0 ]
= [0 0 2 ]
Allocationi= Allocationi+ Requesti
Syeda Sumaiya Afreen pg.
18
R20 CMR Technical Campus
= [0 0 2 ] + [ 3 3 0 ]
= [3 3 2 ]
Needi = Needi–Requesti
= [4 3 1 ] – [ 3 3 0 ]
= [1 0 1 ]
As the resource-request algorithm steps completed, we need to check
the safety algorithm for existence of any safe sequence or not. If safe
sequence exists, then only the changes made by resource-request
algorithms become permanent. Otherwise, its changesare rejected. It
means the new request is rejected.
After inserting the modifications done as per the above, the Allocation,
Max, Need and Available is (Only P4 values and Available matrix
values are changed. Others are same)
P4 - [F F F F F]
So, the system is in not in safe state. As the system is not in safe state,
there is deadlock. Therefore, safe sequence does not exist. As the safe
sequence does not exist, the request made by P4 is rejected and the changes
done by resource-request algorithm are rolled back.
7. DEADLOCK DETECTION
• If deadlocks are not avoided, then another approach is to detect when they
have occurred and recover somehow.
• In addition to the performance hit of constantly checking for deadlocks, a
policy algorithm must be in place for recovering from deadlocks, and there
is potential for lost work when processes must be aborted or have their
resources preempted.
Fig 7.1 - (a) Resource allocation graph. (b) Corresponding wait-for graph
• Write the safety algorithm steps here. It use safety algorithm as discussed in
the above topic (Deadlock Avoidance). If safe sequence exists, then there is
no deadlock. Otherwise there is a deadlock.
• The wait-for graph scheme is not applicable to a resource-allocation system
with multiple instances of each resource type. The algorithm employs
several time-varying data structures that are similar to those used in the
banker's algorithm
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 process.
Request: An n x in matrix indicates the current request of each process. If
R20 CMR Technical Campus
Suppose now that process P2 makes one additional request for an instance
of type C. The Request matrix is modified as follows:
8. DEADLOCK RECOVERY
• Resource preemption
Process Termination:
There are two method to eliminate deadlocks by terminating a process as follows:
• Abort all deadlocked processes: This method will break the deadlock cycle
clearly by terminating all process. This method is cost effective. And it
removes the partial computations completed by the processes.
• Abort one process at a time until the deadlock cycle is eliminated: This
method terminates one process at a time, and invokes a deadlock-detection
algorithm to determine whether any processes are still deadlocked.
Resource Preemption:
In resource preemption, the operator or system preempts some resources
from processes and give these resources to other processes until the deadlock cycle
is broken. If preemption is required to deal with deadlocks, then three issues need
to be addressed:
• Selecting a victim: The system or operator selects which resources and
which processes are to be preempted based on cost factor.
• Rollback: The system or operator must roll back the process to some
safe state and restart it from that state.
• Starvation: The system or operator should ensure that resources will
not always be preempted from the same process.
R20 CMR Technical Campus
do {
entry section
critical section
exit section
remainder section
} while (TRUE);
• Critical Section: This part allows one process to enter and modify the shared
variable.
• Exit Section: Exit section allows the other processes that are waiting in the
Entry Section, to enter into the Critical Sections.
R20 CMR Technical Campus
• Remainder Section: All other parts of the Code, which is not shared (code
other than in Critical, Entry, and Exit Section), are known as the Remainder
Section.
Peterson’s solution
boolean
flag[2]; int
turn;
Initially, the value of flag [0] = flag[1] = false. The variable turn indicates
whose turn to execute the critical section. For example, when process P0 executes, i
= 0 and j = 1. If process P1 executes, i = 1 and j = 0. The structure of Peterson’s
solution is given as:
R20 CMR Technical Campus
When, the process Px wants to enter into critical section, it first assigns
flag[i] = true. Then it sets the 'turn = j' by assuming that if other process wants to
enter the critical section. When both processes are attempted to enter at the same
time, the 'turn' value will be set to both ‘i’ and ‘ j’ roughly at the same time. But,
one assignment is last and other will be saved in turn. So, only one process is
allowed to enter critical section depending on turn value.
2. SYNCHRONIZATION HARDWARE
• One simple solution to the critical section problem is to simply prevent a process
from being interrupted while in their critical section, which is the approach
taken by non preemptive kernels. Unfortunately this does not work well in
multiprocessor environments, due to the difficulties in disabling and the re-
enabling interrupts on all processors. There is also a question as to how this
approach affects timing if the clock interrupt is disabled.
• Another approach is for hardware to provide certain atomic operations. These
operations are guaranteed to operate as a single instruction, without interruption.
R20 CMR Technical Campus
One such operation is the "Test and Set", which simultaneously sets a boolean
lock variable and returns its previous value, as shown in Figures below:
3. SEMAPHORES
Semaphores are integer variables that are used to solve the critical section problem
by using two atomic operations wait and signal. Initial value for S = 1.
• First we create a semaphore named synch that is shared by the two processes,
and initialize it to zero.
S1;
signal( synch );
wait( synch );
S2;
Because synch was initialized to 0, process P2 will block on the wait until after
P1 executes the call to signal.
do
{ waiting(mutex);
// critical section
signal(mutex);
// remainder section
}while (TRUE);
R20 CMR Technical Campus
Semaphore Implementation
The big problem with semaphores as described above is the busy loop in
the wait call, which consumes CPU cycles without doing any useful work. This
type of lock is known as a spinlock, because the lock just sits there and spins
while it waits. While this is generally a bad thing, it does have the advantage of
not invoking context switches, and so it is sometimes used in multi-processing
systems when the wait time is expected to be short - One thread spins on one
processor while another completes their critical section on another processor.
There are five philosophers sitting around a table. There are five
chopsticks/forks kept on the table such that in between every two philosophers
one chopstick is placed. A bowl of rice is placed in the centre of the table.
When a philosopher wants to eat, he must use two chopsticks - one from their
immediate left and one from their immediate right. When a philosopher wants
to think, he keeps down both chopsticks at their original place.
• Solution 1: No hold and wait: No philosopher is allowed to hold one
chopstick and wait for second chopstick. A philosopher has to take the
chopsticks if both chopsticks are available.
• Solution 2: Allow up to n-1 philosophers: Allowing up to maximum of n-1
(in our case 4) philosophers to eat at any time, then there is a chance of one
philosopher can eat.
• Solution 3: Even-odd philosopher: According to sitting order of
Philosophers, serial numbers are assigned starting from 1. Even number
philosophers are allowed to take their right chopstick first and then take left
chopstick. Odd number philosophers are allowed to take their left chopstick
first and then take right chopstick later.
do {
wait (chopstick [i] );
wait(chopstick [ (i + 1) % 5] ) ;
// eat
signal(chopstick [i]);
signal(chopstick [(i + 1) % 5]);
/ / think
}while (TRUE);
Fig 4.3 : The structure of philosopher i.
5. MONITORS
• Semaphores can be very useful for solving concurrency problems, but only if
programmers use them properly. If even one process fails to abide by the
proper use of semaphores, either accidentally or deliberately, then the whole
system breaks down. ( And since concurrency problems are by definition rare
events, the problem code may easily go unnoticed and/or be heinous to debug. )
• For this reason a higher-level language construct has been developed, called
monitors.
Monitor Usage
• A monitor is essentially a class, in which all data is private, and with the special
restriction that only one method within any given monitor object may be active
Syeda Sumaiya Afreen pg.
37
R20 CMR Technical Campus
at the same time. An additional restriction is that monitor methods may only
access the shared data within the monitor and any data passed to them as
parameters. I.e. they cannot access any data external to the monitor.
• But now there is a potential problem - If process P within the monitor issues a
signal that would wake up process Q also within the monitor, then there would
be two processes running simultaneously within the monitor, violating the
exclusion requirement. Accordingly there are two possible solutions to this
dilemma:
Signal and wait - When process P issues the signal to wake up process Q, P then
waits, either for Q to leave the monitor or on some other condition.
Signal and continue - When P issues the signal, Q waits, either for P to exit the
monitor or for some other condition.
There are arguments for and against either choice. Concurrent Pascal offers a third
alternative - The signal call causes the signaling process to immediately exit the
monitor, so that the waiting process can then wake up and proceed.
• Java and C# ( C sharp ) offer monitors bulit-in to the language. Erlang offers
similar but different constructs.
Process A Process A
Operating System
Syeda Sumaiya Afreen pg.
40
R20 CMR Technical Campus
a. Pipes
b. Named pipes or FIFO
c. Message Queues
d. Shared Memory
b. FIFO: Pipes were meant for communication between related processes. We can
also use pipes for unrelated process communication. In this case named pipe also
known as FIFO (First-In- First-Out) is used. The mechanism used in FIFO is
full duplex meaning, same single named pipe can be used for two-way
communication (communication between the server and the client, plus the client
and the server at the same time). The Named Pipe supports bi-directional
communication.