OS Unit3
OS Unit3
me/jntuh
UNIT - III
DEADLOCK
A process in operating system uses resources in the following way.
(i) Requests a resource
(ii) Use the resource
(iii) Releases the resource
A deadlock is a situation where a set of processes are blocked because each
process is holding a resource and waiting for another resource acquired by some
other process.
Consider an example when two trains are coming toward each other on the
same track and there is only one track, none of the trains can move once they are
in front of each other.
A similar situation occurs in operating
systems when there are two or more processes that
hold some resources and wait for resources held
by other(s). For example, in the below diagram,
Process1 is holding Resource1 and waiting for
Rsource2 which is acquired by Process2, and
Process2 is waiting for Resource1.
Examples of Deadlock
1. The system has 2 tape drives. P1 and P2 each hold one tape drive and each
needs another one.
2. Semaphores A and B, initialized to 1, P0, and P1 are
P0 P1
in deadlock as follows:
P0 executes wait(A) and preempts.
wait(A); wait(B)
P1 executes wait(B).
Now P0 and P1 enter in deadlock.
wait(B); wait(A)
3. Assume the space is available for allocation of 200K bytes, and the
following sequence of events occurs.
P0 P1
Request Request
80KB; 70KB;
Request Request
60KB; 80KB;
Example
Consider 3 processes P1, P2 and P3 and two
types of resources R1 and R2. The resources are
having 1 instance each.
According to the graph, R1 is being used by
P1, P2 is holding R2 and waiting for R1, P3 is
waiting for R1 as well as R2.
The graph is deadlock free since no cycle is
being formed in the graph.
Rule-01: In a Resource Allocation Graph where all the resources are single
instance,
If a cycle is being formed, then system is in a deadlock state.
If no cycle is being formed, then system is not in a deadlock state.
Rule-02: In a Resource Allocation Graph where all the resources are NOT single
instance,
If a cycle is being formed, then system may be in a deadlock state.
Banker’s Algorithm is applied to confirm whether system is in a deadlock
state or not.
If no cycle is being formed, then system is not in a deadlock state.
Presence of a cycle is a necessary but not a sufficient condition for the
occurrence of deadlock.
Allow pre-emption
Preempt resources from the process when resources are required by other
high-priority processes.
AVOIDANCE
Avoidance is kind of futuristic. By using the strategy of “Avoidance”, we
have to make an assumption. We need to ensure that all information about
resources that the process will need is known to us before the execution of the
process.
3) Deadlock ignorance:
If a deadlock is very rare, then let it happen and reboot the system. This is
the approach that both Windows and UNIX take. We use the ostrich algorithm
for deadlock ignorance.
In Deadlock, ignorance performance is better than the above two methods
but not the correctness of data.
SAFE STATE
A safe state can be defined as a state in which there is no deadlock. It is
achievable if:
If a process needs an unavailable resource, it may wait until the same has
been released by a process to which it has already been allocated. if such a
sequence does not exist, it is an unsafe state.
All the requested resources are allocated to the process.
BANKER'S ALGORITHM
It is a banker algorithm used to avoid deadlock and allocate
resources safely to each process in the computer system. The 'S-State' examines
all possible tests or activities before deciding whether the allocation should be
allowed to each process. It also helps the operating system to successfully share
the resources between all the processes.
The banker's algorithm is named because it checks whether a person should
be sanctioned a loan amount or not to help the bank system safely simulate
allocation resources.
Suppose the number of account holders in a particular bank is 'n', and the
total money in a bank is 'T'. If an account holder applies for a loan; first, the bank
subtracts the loan amount from full cash and then estimates the cash difference is
greater than T to approve the loan amount. These steps are taken because if
another person applies for a loan or withdraws some amount from the bank, it
helps the bank manage and operate all things without any restriction in the
functionality of the banking system.
Similarly, it works in an operating system. When a new process is created
in a computer system, the process must provide all types of information to
the operating system like upcoming processes, requests for their resources,
counting them, and delays.
Based on these criteria, the operating system decides which process
sequence should be executed or waited so that no deadlock occurs in a system.
Therefore, it is also known as deadlock avoidance algorithm or deadlock
detection in the operating system.
Following are the important data structures terms applied in the banker's
algorithm as follows:
Suppose n is the number of processes, and m is the number of each type of
resource used in a computer system.
1. Available: It is an array of length 'm' that defines each type of resource
available in the system. When Available[j] = K, means that 'K' instances of
Resources type R[j] are available in the system.
2. Max: It is a [n x m] matrix that indicates each process P[i] can store the
maximum number of resources R[j] (each type) in a system.
3. Allocation: It is a matrix of m x n orders that indicates the type of
resources currently allocated to each process in the system. When
Allocation [i, j] = K, it means that process P[i] is currently allocated K
instances of Resources type R[j] in the system.
4. Need: It is an M x N matrix sequence representing the number of
remaining resources for each process. When the Need[i] [j] = k, then
process P[i] may require K more instances of resources type Rj to complete
the assigned work.
Need[i][j] = Max[i][j] - Allocation[i][j].
5. Finish: It is the vector of the order m. It includes a Boolean value
(true/false) indicating whether the process has been allocated to the
requested resources, and all resources have been released after finishing its
task.
The Banker's Algorithm is the combination of the safety algorithm and the
resource request algorithm to control the processes and avoid deadlock.
Safety Algorithm
It is a safety algorithm used to check whether or not a system is in a safe
state or follows the safe sequence in a banker's algorithm:
Step1:
There are two vectors Wok and Finish of length m and n in a safety
algorithm.
Initialize: Work = Available
Finish[i] = false; for I = 0, 1, 2, 3, 4… n - 1.
Step2:
Check the availability status for each type of resources [i], such as:
Need[i] <= Work
Finish[i] == false
If the i does not exist, go to step 4.
C. Dinesh, AP/CSE-AIML, MRCE Page 7
Step3:
Work = Work +Allocation(i) // to get new resource allocation
Finish[i] = true
Go to step2 to check the status of resource availability for the next process.
Step4:
If Finish[i] == true; it means that the system is safe for all processes.
When the resource allocation state is safe, its resources are allocated to the
process P(i). And if the new state is unsafe, the Process P (i) has to wait for each
type of Request R(i) and restore the old resource-allocation state.
Example:
Consider a system that contains five processes P1, P2, P3, P4, P5 and the
three resource types A, B and C. Following are the resources types: A has 10, B
has 5 and the resource type C has 7 instances.
P1 0 1 0 7 5 3 3 3 2
P2 2 0 0 3 2 2
P3 3 0 2 9 0 2
P4 2 1 1 2 2 2
P5 0 0 2 4 3 3
Answer the following questions using the banker's algorithm:
1. What is the reference of the need matrix?
2. Determine if the system is safe or not.
3. What will happen if the resource request (1, 0, 2) for process P1 can the
system accept this request immediately?
4. What will happen if the resource request (3, 3, 0) for process P5?
5. What will happen if the resource request (0, 2, 0) for process P1?
Ans.1:
Context of the need matrix is as Need [i] = Max [i] - Allocation [i]
Need for P1: (7, 5, 3) - (0, 1, 0) = 7, 4, 3
Need for P2: (3, 2, 2) - (2, 0, 0) = 1, 2, 2 Process Need
Need for P3: (9, 0, 2) - (3, 0, 2) = 6, 0, 0 A B C
Need for P4: (2, 2, 2) - (2, 1, 1) = 0, 1, 1
Need for P5: (4, 3, 3) - (0, 0, 2) = 4, 3, 1 P1 7 4 3
P2 1 2 2
P3 6 0 0
P4 0 1 1
P5 4 3 1
Step 6:
For Process P1:
P1 Need <= Available
7, 4, 3 <= 7, 4, 5 condition is true
New Available Resource = Available + Allocation
7, 4, 5 + 0, 1, 0 => 7, 5, 5
So, we examine another process P2.
Step 7:
For Process P3:
P3 Need <= Available
6, 0, 0 <= 7, 5, 5 condition is true
New Available Resource = Available + Allocation
7, 5, 5 + 3, 0, 2 => 10, 5, 7
Hence, we execute the banker's algorithm to find the safe state and the safe
sequence like P2, P4, P5, P1 and P3.
Ans. 3:
For granting the Request (1, 0, 2), first we have to check that
Request <= Available, that is (1, 0, 2) <= (3, 3, 2),
Since the condition is true, the process P2 may
get the request immediately.
Process Need
Allocation for P2 is (3,0,2) and new Available A B C
is (2, 3, 0)
Context of the need matrix is as follows: P1 7 4 3
Need [i] = Max [i] - Allocation [i]
Need for P1: (7, 5, 3) - (0, 1, 0) = 7, 4, 3 P2 0 2 0
Need for P2: (3, 2, 2) - (3, 0, 2) = 0, 2, 0 P3 6 0 0
Need for P3: (9, 0, 2) - (3, 0, 2) = 6, 0, 0
Need for P4: (2, 2, 2) - (2, 1, 1) = 0, 1, 1 P4 0 1 1
Need for P5: (4, 3, 3) - (0, 0, 2) = 4, 3, 1
P5 4 3 1
Step 1:
For Process P1:
Need <= Available
7, 4, 3 <= 2, 3, 0 condition is false.
So, we examine another process, P2.
Step 2:
For Process P2:
Need <= Available
1, 2, 2 <= 2, 3, 0 condition true
New available = available + Allocation
(2, 3, 0) + (3, 0, 2) => 5, 3, 2
Similarly, we examine another process P3.
Step 3:
For Process P3:
P3 Need <= Available
6, 0, 0 < = 5, 3, 2 condition is false.
Similarly, we examine another process, P4.
Step 4:
For Process P4:
P4 Need <= Available
0, 1, 1 <= 5, 3, 2 condition is true
New Available resource = Available + Allocation
5, 3, 2 + 2, 1, 1 => 7, 4, 3
Similarly, we examine another process P5.
Step 5:
For Process P5:
P5 Need <= Available
4, 3, 1 <= 7, 4, 3 condition is true
New available resource = Available + Allocation
7, 4, 3 + 0, 0, 2 => 7, 4, 5
Now, we again examine for processes P1 and P3.
Step 6:
For Process P1:
P1 Need <= Available
7, 4, 3 <= 7, 4, 5 condition is true
New Available Resource = Available + Allocation
7, 4, 5 + 0, 1, 0 => 7, 5, 5
So, we examine another process P2.
C. Dinesh, AP/CSE-AIML, MRCE Page 12
Step 7:
For Process P3:
P3 Need <= Available
6, 0, 0 <= 7, 5, 5 condition is true
New Available Resource = Available + Allocation
7, 5, 5 + 3, 0, 2 => 10, 5, 7
Hence, P2 granted immediately and the safe sequence like P2, P4, P5, P1
and P3.
Ans. 4:
For granting the Request (3, 3, 0) by P5, first we have to check that
Request <= Available, that is (3, 3, 0) <= (2, 3, 0),
Since the condition is false. So the request for (3, 3, 0) by process P5
cannot be granted.
Ans. 5:
For granting the Request (0, 2, 0) by P1, first we have to check that
Request <= Available, that is (0, 2, 0) <= (2, 3, 0),
Since the condition is true. So the request for (0, 2, 0) by process P1 may be
granted.
Allocation for P1 is (0, 3, 0) Process Need
Context of the need matrix is as follows: A B
Need [i] = Max [i] - Allocation [i] C
Need for P1: (7, 5, 3) - (0, 3, 0) = 7, 2, 3
P1 7 2 3
DEADLOCK DETECTION
If a system does not employ either a deadlock prevention or deadlock
avoidance algorithm then a deadlock situation may occur. In this case-
Apply an algorithm to examine the system‟s state to determine whether
deadlock has occurred.
Apply an algorithm to recover from the deadlock.
For example,
10. i=4 is selected as both Finish[4] = false and [0, 0, 2]<=[7, 2, 4].
11. Work =[7, 2, 4]+[0, 0, 2] =>[7, 2, 6] &
Finish = [true, true, true, true, true].
12. Since Finish is a vector of all true it means there is no deadlock in this
example.
1. Wait-For Graph:
A graphical representation of the system‟s processes and resources. A directed
edge is created from a process to a resource if the process is waiting for that
resource. A cycle in the graph indicates a deadlock.
2. Banker’s Algorithm:
A resource allocation algorithm that ensures that the system is always in a safe
state, where deadlocks cannot occur.
5. Timestamping:
Each process is assigned a timestamp, and the system checks to see if any
process is waiting for a resource that is held by a process with a lower timestamp.
These algorithms are used in different operating systems and systems with
different resource allocation and synchronization requirements. The choice of
algorithm depends on the specific requirements of the system and the trade-offs
between performance, complexity and accuracy.
Race Condition
A race condition is a condition when there are many processes and every
process shares the data with each other and accessing the data concurrently and the
output of execution depends on a particular sequence in which they share the data
and access.
(OR)
When more than one process is executing the same code or accessing the
same memory or any shared variable in that condition there is a possibility that the
output or the value of the shared variable is wrong so for that all the processes
doing the race to say that my output is correct. This condition is known as race
condition.
Several processes access and process the manipulations over the same data
concurrently, then the outcome depends on the particular order in which the access
takes place.
Example:
Let‟s say there are two processes P1 and P2 which share common variable
(shared=10), both processes are present in ready – queue and waiting for its turn to
be execute.
Suppose, Process P1 first come under
Process 1 Process 2
execution, initialized as X=10 and increment it
by 1 (ie.X=11), after then when CPU read line
sleep(1), it switches from current process P1 to int X = shared int Y = shared
process P2 present in ready-queue. The process
P1 goes in waiting state for 1 second. X++ Y--
Now CPU execute the Process P2,
initialized Y=10 and decrement Y by sleep(1) sleep(1)
1(ie.Y=9), after then when CPU read sleep(1),
the current process P2 goes in waiting state and shared = X shared = Y
CPU remains idle for sometime as there is no
process in ready-queue.
After completion of 1 second of process P1 when it comes in ready-queue,
CPU takes the process P1 under execution and execute the remaining line of code
and shared=11.
After completion of 1 second of Process P2, when process P2 comes in
ready-queue, CPU start executing the further remaining line of Process P2 and
shared=9.
Note:
We are assuming the final value of common variable(shared) after
execution of Process P1 and Process P2 is 10 (as Process P1 increment variable by
1 and Process P2 decrement variable by 1 and finally it becomes shared=10). But
we are getting undesired value due to lack of proper synchronization.
PETERSON’S SOLUTION
Peterson‟s Solution is a classical software-based solution to the critical section
problem. In Peterson‟s solution, we have two shared variables:
boolean flag[i]: Initialized to FALSE, initially no one is interested in
entering the critical section
int turn: The process whose turn is to enter the critical section.
SEMAPHORES
Semaphore is a Hardware Solution. This Hardware solution is written or
given to critical section problem. The Semaphore is just a normal integer. The
Semaphore cannot be negative. The least value for a Semaphore is zero (0). The
Maximum value of a Semaphore can be anything. The Semaphores usually have
two operations. The two operations have the capability to decide the values of the
semaphores.
The two Semaphore Operations are:
1. Wait ( )
2. Signal ( )
Definition of wait()
wait(Semaphore S)
{
while (S<=0) ; //no operation
S--;
}
Definition of signal()
signal(S)
{
S++;
}
A producer tries to insert data into an empty slot of the buffer. A consumer
tries to remove data from a filled slot in the buffer. There needs to be a way to
make the producer and consumer work in an independent manner.
One solution of this problem is to use semaphores. The semaphores which
will be used here are:
m, a binary semaphore which is used to acquire and release the lock.
empty, a counting semaphore whose initial value is the number of
slots in the buffer, since, initially all slots are empty.
full, a counting semaphore whose initial value is 0.
At any instant, the current value of empty represents the number of empty
slots in the buffer and full represents the number of occupied slots in the buffer.
} while(TRUE);
Looking at the above code for a producer, we can see that a producer first
waits until there is atleast one empty slot.
Then it decrements the empty semaphore because, there will now be one
less empty slot, since the producer is going to insert data in one of those
slots.
Then, it acquires lock on the buffer, so that the consumer cannot access the
buffer until producer completes its operation.
After performing the insert operation, the lock is released and the value
of full is incremented because the producer has just filled a slot in the
buffer.
} while(TRUE);
The consumer waits until there is atleast one full slot in the buffer.
Then it decrements the full semaphore because the number of occupied
slots will be decreased by one, after the consumer completes its operation.
After that, the consumer acquires lock on the buffer.
Following that, the consumer completes the removal operation so that the
data from one of the full slots is removed.
Then, the consumer releases the lock.
Finally, the empty semaphore is incremented by 1, because the consumer
has just removed data from an occupied slot, thus making it empty.
Dining-Philosophers Problem
The Dining Philosopher Problem states that K philosophers seated around a
circular table with one chopstick between each pair of philosophers. There is
one chopstick between each philosopher. A philosopher may eat if he can
pickup the two chopsticks adjacent to him. One chopstick may be picked up by
any one of its adjacent followers but not both. This problem involves the
allocation of limited resources to a group of processes in a deadlock-free and
starvation-free manner.
Reader process
Reader requests the entry to critical section.
If allowed:
it increments the count of number of readers inside the critical
section. If this reader is the first reader entering, it locks
the wrt semaphore to restrict the entry of writers if any reader is
inside.
It then, signals mutex as any other reader is allowed to enter while
others are already reading.
After performing reading, it exits the critical section. When exiting,
it checks if no more reader is inside, it signals the semaphore “wrt”
as now, writer can enter the critical section.
If not allowed, it keeps on waiting.
do
{
wait(mutex); // Reader wants to enter the critical section
readcnt++; // The number of readers has now increased by 1
} while(true);
Writer process
1. Writer requests the entry to critical section.
2. If allowed i.e. wait() gives a true value, it enters and performs the
write. If not allowed, it keeps on waiting.
3. It exits the critical section.
do
{
wait(wrt); // writer requests for critical section
…perform WRITING
} while(true);
MONITOR
It is a synchronization technique that enables threads to mutual exclusion
and the wait() for a given condition to become true. It is an abstract data type. It
has a shared variable and a collection of procedures executing on the shared
variable. A process may not directly access the shared data variables, and
procedures are required to allow several processes to access the shared data
variables simultaneously.
At any particular time, only one process may be active in a monitor. Other
processes that require access to the shared variables must queue and are only
granted access after the previous process releases the shared variables.
Syntax:
monitor
{
//shared variable declarations
data variables;
Procedure P1() { ... }
Procedure P2() { ... }
.
.
.
Procedure Pn() { ... }
Initialization Code() { ... }
}
Advantages
Mutual exclusion is automatic in monitors.
Monitors are less difficult to implement than semaphores.
Monitors may overcome the timing errors that occur when semaphores are
used.
Monitors are a collection of procedures and condition variables that are
combined in a special type of module.
Disadvantages
Monitors must be implemented into the programming language.
The compiler should generate code for them.
It gives the compiler the additional burden of knowing what operating
system features is available for controlling access to crucial sections in
concurrent processes.
C. Dinesh, AP/CSE-AIML, MRCE Page 32
Action The semaphore's value shows the The Monitor type includes
number of shared resources shared variables as well as a set
available in the system. of procedures that operate on
them.