OS 4 Synchronization & Deadlock
OS 4 Synchronization & Deadlock
When two or more processes cooperate with each other, the order of execution of both
processes must be preserved otherwise it can generate conflicts while execution and also
result in inappropriate outputs.
The procedure which is involved in preserving the order of execution of cooperative processes
is called Process Synchronization. We have various synchronization mechanisms which are
being used in process synchronization.
Need of Synchronization-
● When two or more processes execute concurrently while sharing some system resources,
So, all these processes execute properly, we need proper synchronization between their
actions.
● Process synchronization avoids inconsistent output.
Critical Section-
Critical section is a small piece of code or a section in the program from where a process
accesses the shared resources concurrently during its execution.
Race Condition-
Race condition is defined as a situation when two or more processes run concurrently and
using some shared resource, so -
● The final output produced completely depends upon the execution order of instructions of
processes.
● Some processes compete with each other.
Critical Section Problem-
● The issue with the critical section is if two or more processes access the critical section
concurrently, then the resulting output might be inconsistent. This inconsistency is
referred to as the Critical Section Problem.
2.1. Synchronization Mechanisms-
Synchronization Mechanism allows various processes to access critical section code in a
synchronized way, to avoid inconsistent outputs.
For every critical section code in the program,
● An entry section is added by the synchronization mechanism before the critical section
● An exit section is added by the synchronization mechanism after the critical section
Entry Section-
● It behaves as an entry gate for a process before entering into the critical section.
● It ensures that at any time only one process should be present inside the critical
section.
● It disallows any other process to enter into the critical section if one process is already
present in the critical section.
Exit Section-
● It acts as an exit gate for a process when it leaves the critical section.
● When a process exits from the critical section, some small changes are made so that
another process can enter inside the critical section to use it.
1. Mutual Exclusion
2. Progress
3. Bounded Wait
1. Mutual Exclusion-
● All processes should access the critical section in a mutually exclusive manner.
● At any time only one process should be present inside the critical section.
● Disallow any other process to enter into the critical section if one process is already
present in the critical section. No other process can access the critical section
● Entry of a process into the critical section must be independent of the entry of any
other process inside the critical section.
● If no other process is present inside it, then a process can freely enter into the
critical section.
● A process will get into the critical section only if it wants to.
● No process should be forced to enter into the critical section if the process does not
want to enter.
3. Bounded Wait-
● The waiting time of a process to enter into the critical section must be bounded.
● A process should be entered into the critical section before its waiting time gets over.
3. SEMAPHORES IN OS
Types of Semaphores-
1. Counting Semaphores
⮚ An integer values
⮚ Positive value shows the total number of processes that are present in the critical
section at a time.
⮚ Negative value shows the total number of processes that are blocked in the
waiting list(queue).
● Operations on Semaphore
operations were computed on that semaphore. What will be the resulting value of
Solution-
S = 14 (initial)
8 P (wait):
S = S -8
= 14 - 8 = 6
then 3 V:
S=S+3
● The waiting list(queue) of binary semaphores indicates the processes that are
● When a process tries to enter the critical section, the wait operation is
executed. Two cases are possible-
● The value of the binary semaphore is set to 0 if any process is allowed to enter the
critical section.
● No process is allowed to enter into the critical section, the process is blocked, and
the process is kept in the waiting queue.
● When a process takes exit from the critical section the signal operation is
● If the waiting queue (blocked queue) is empty, then the value of the binary
semaphore will be set to 1.
Case-02: Waiting List is Not Empty-
If the waiting list/queue is not empty, then a process is selected from the waiting list and
executed
Example- Let suppose S be the binary semaphore variable and initialized to S=1.
Assuming there are no blocked processes in the system. If the following sequence of
operations is performed, then how many processes are blocked in the system at the
end of operations?
A. 0
B. 14
C. 15
D. 12
Answer- B
Solution-
Initially, S=1
Operation- 7V
Operation- 5P
1st down operation is successful, S=0, then no more successful down operations are
possible
For the remaining 4P operation, the four processes, let's say P1, P2, P3 and P4 are
Operation- 14V
For the first 4V up operations, the processes P1, P2, P3 and P4 are taken out from the
Blocked list. For 5th V operation, S=1, and for the remaining V operation S will remain
the same as 1.
Operation- 10P
1st down operation is successful, S=0, further no more successful down operation
possible For the remaining 9P, the nine processes, let’s say P1, P2…, P9 are inserted
For first 9V operations, the processes P1, P2, P3, …, P9 are taken out from the Blocked
list. For 10th up operation, S will become 1, and for the remaining V operation S
Operation-15P
For the remaining 14P, the 14 processes, let’s say P1, P2…, P14 are inserted into the
Blocked queue.
Hence, after executing all operations total 14 processes are in the Blocked queue.
Problem Description: A barbershop has a waiting room with n number of chairs and
● If there are zero customers in the shop, the barber will go and sleep.
● If any customer comes to the barbershop and all none of the chairs are empty, then
● If the barber is busy with some customers but chairs are empty, then the customer
● If the barber is sleeping, and a customer arrives, the customer will wake up the barber.
semaphore customers.
We also require a semaphore (cutting). It will ensure that the barber won’t cut another
// shared data
semaphore customers = 0;
semaphore barbers = 0;
semaphore cutting = 0;
semaphore mutex = 1;
int customer1 = 0;
void barber () {
while(true) {
customers1 = customers1 - 1;
signal(barbers);
signal(mutex);
cut_hair();
void customer () {
if (customers1 < n) {
customers1 = customers1 + 1;
signal(customers);
signal(mutex);
get_haircut();
else {
signal(mutex);
cut_hair(){
waiting(cutting);
get_haircut(){
signal(cutting);
Solution:
● If the total number of customers = number of chairs in the waiting room, then the
When the barber comes in the morning, he has to execute the procedure barber, this
will cause him to block the semaphore customers because initially it is 0. Then the
When a customer arrives, he executes the customer code and the customer holds the
mutex for entering into the critical section, if another customer enters after the first
customer, the second one will not do anything until the first customer has released the
mutex. Then, the customer will check for the available number of chairs in the waiting
room if the number of waiting customers are less than the total number of chairs then a
customer will sit in the waiting chair otherwise, he will leave the barber shop and
If the waiting chair is available, then the customer will sit in it and will increment the
value of variable waiting and it will also increase the customers semaphore. This will
Now, the customer and the barber both are awake so the barber will give a haircut to
that person. When the haircut is done, the customer will exit the procedure and if there
are no customers in the waiting room the barber will sleep again otherwise give a
there are five philosophers sharing a circular dining table and do only two tasks either
they will eat, or they will think. A bowl of rice is kept for each of the philosophers and
there are five chopsticks on the table. If a philosopher is eating so he will require both
right and left chopsticks. A philosopher will only eat if both chopsticks are available.
The chopstick is initialized to 1 as initially we are assuming that the chopsticks are on the
do {
wait( chopstick[i] );
.
. EATING THE RICE
signal( chopstick[i] );
. THINKING
} while (1);
In the above solution, the first wait(P) operation is performed on chopstick[i] and
chopstick [ (i+1) % 5]; which means the philosopher i has picked up the chopsticks.
After this, signal(V) operation is performed on chopstick[i] and chopstick [ (i+1) % 5];
which means the philosopher i has eaten the rice and put down the chopsticks on his
The above proposed solution ensures that no two neighbouring philosophers can eat the
food at the same time. But in some cases, this solution can cause a deadlock. Deadlock
may occur if all the philosophers want to eat and pick up their left chopstick
simultaneously. Then no one of them can eat the food and a deadlock occurs.
● Even numbered philosophers should pick the right chopstick then the left chopstick
whereas an odd numbered philosopher should pick the left chopstick first and then
● A philosopher should pick his chopstick only if both chopsticks are available at the
same time.
There are some processes (readers) they only read the shared data, and never alter it,
and there are some other processes(writers) who have permission to change/write the
● At a time, any number of readers can read data from the shared resource, but only
one writer is allowed to write into the shared resource.
● When a writer is writing/ changing the data to the resource, non-other process is
allowed to access the resource.
● If there are non-zero no. of readers reading the resource at the same time. Then,
Writer cannot perform write operation
Solution of Reader Writers Problem-
If a writer wishes to perform write operation to the resource, so he must wait until all
readers leave the system.
Here,
● we are using one mutex m and a semaphore w.
● read_count is an integer variable; it is used to maintain the no. of readers accessing
the resource at a time. This variable is initialized to 0.
● Initially, m and w are started with the value 1.
● The writer just waits on the semaphore w until all the readers leave the resource and
writer gets a chance to write data to the resource.
● Once the write operation is performed, semaphore w will be incremented so that the
next writer can access the resource to write.
● Whereas, In the reader’s code, the lock is acquired by the reader whenever
● Whenever a reader wants to read/access the resource, first of all it will increment
the read_count value, then read the data from the resource and once its operation
● The semaphore w is used and modified by the first and last reader who enters and
exits the critical section respectively. Because, when the first reader enters into the
critical section, the writer will be blocked from the resource. Now, new readers can
● Similarly, when the last reader leaves the critical section, it signals(V) the writer by
using the semaphore w because right now there are no readers in the system and a
5. SYNCHRONIZATION MECHANISMS
5.1. Lock Variable
This is one of the simplest synchronization mechanisms. Lock variable is a software
mechanism which is implemented in User mode. This is a solution to busy waiting that
can be used for more than two processes.
In this mechanism, lock can either be 0 or 1. If Lock value is 0 it means that the C.S is
empty and if the lock value is 1 it means C.S. is occupied.
If a process wants to access the critical section, it must check the value of the lock
variable, if the value is 0 then change it to 1 and let the process enter into the critical
section, and if the value of lock is 1 then wait.
Pseudo code of the lock mechanism -
Entry Section →
While (lock! = 0);
Lock = 1;
//Critical Section
Exit Section →
Lock =0;
Initially, the lock variable’s value is 0.
● If Lock value = 0 it means the CS is currently empty and no process is present in it.
● If Lock value = 1 it means the CS is currently filled and a process is present in
it. Characteristics of Lock variable synchronization mechanism-
● Used in numerous processes.
● It is a solution for busy waiting, when the process is actually waiting the lock variable
keeps the CPU busy.
Failure of the Lock Variable Mechanism-
● Lock variable mechanism completely failed to provide synchronization among the
different processes.
● It can’t guarantee to meet the basic criteria of mutual exclusion.
5.2. Test and Set Lock –
● Test and Set Lock (TSL) is another synchronization mechanism.
● It makes use of a test and set instruction to maintain the synchronization among the
concurrently executing processes.
The os provides a special instruction set known as Test Set Lock (TSL) instruction
whose responsibility is to load the lock variable’s value into the local register R0 and
sets it to 1.
The process in which TSL is executed first that process will enter into the CS and after
that no other process can enter into the critical section until the first process comes out.
No process can access the critical section even if the first process is being pre-empted.
2. CMP R0, #0
3. JNZ step 1
Mutual Exclusion
Progress
In the TSL mechanism, the TSL instruction will only be executed in a process if the process
itself wants to enter into the critical section. And, according to the definition, Progress is
defined as when a process who itself doesn’t want to get into the critical section should
not stop any other process from entering into it. The lock variable’s value will always be
0 if no other process wants to enter the critical section. Hence, progress is also
guaranteed in TSL.
Bounded Waiting
This condition is not guaranteed in TSL. We cannot say that a process will definitely get
a chance to enter the critical section after a certain time, some processes may not get a
chance for a long time. So, bounded waiting is not guaranteed in the Test and Set Lock
synchronisation mechanism.
Characteristics of TSL synchronization mechanism are-
In the TSL mechanism, there exists a problem of priority inversion. Let’s suppose that
and gets scheduled by the CPU. As it is a cooperative process, and it will execute in the
critical section so it will enter in the CS and set the lock variable to 1.
Now, P2 arrives, and we know that the priority of P1 is lower than P2, so according to
is also a cooperative process, and it also wants to enter into the critical section for
execution.
P1 got pre-empted but the value of the lock variable will be 1 because P1 is not completed,
P1 needs to complete its execution in the critical section but scheduling algorithm says,
CPU is with process P2. Now, P2 wants to enter into the critical section to complete
execution, but the synchronization mechanism says the critical section is with P1.
Such a kind of lock is known as Spin Lock where each of the processes neither
This is not a deadlock because none of the processes are in a blocked state. One
process is in the ready state and the other process is in the running state, but none of
This approach is used only for two processes. Let us consider two processes to be P0
and P1. They share a common variable called turn variable.
Pseudocode is defined as following:
The problem of the lock variable method is that the process can enter into the critical
section, only when the lock variable is 1. And more than one processes are able to see
the lock variable as 1 simultaneously.
Characteristics of Turn Variable-
● Ensures mutual exclusion.
● Follows a strict alternation approach, so progress is not guaranteed.
● Ensures bounded waiting because processes execute one by one and there is a
guarantee that each process will get a chance to execute.
● Starvation doesn’t exist.
● It is neutral architecturally because it doesn’t need any support of the operating
system.
● Deadlock free.
● It is a solution to busy waiting.
5.4. Strict Alternation
Approach
In strict alternation approach,
● Processes have to enter the critical section compulsorily in an alternate order
whether they want to enter or not.
● This happens because if one process doesn't want to enter the critical section, then
the other process will never get a chance to execute again in the critical section.
Interest Variable-
● It is a synchronization mechanism that synchronize instruction between two processes.
● It uses a variable named interest to synchronise
processes. Its implementation is as follows-
6. INTRODUCTION DEADLOCK
next chance.
A Deadlock is a situation where each of the computer processes waits for a resource which
is being assigned to some other process. In this situation, none of the process gets
executed since the resource it needs is held by some other process which is also waiting
for some other resource to be released.
Example-
Here
• Process P1 holds resource R1 and waits for resource R2 which is held by process P2.
• Process P2 holds resource R2 and waits for resource R1 which is held by process P1.
• None of the two processes can complete and release their resource.
• Thus, both the processes keep waiting infinitely.
Alternate-
Using the: Formula-: 𝑛(𝑥 − 1) + 1 ≤ 𝑟
Where, n= number of processes, x=need for each process, r= total instances of
resource. “The above formula states that, the number of resources r must be greater
than the overall need of all the processes”
Here, n= 3, number of processes given in problem
x=2, each process requires 2 unit of resource
r=? we need to find the minimum resources to ensure no deadlock occurs.
Putting the values in above formula,
3(2 − 1) + 1 ≤ 𝑟
3+1≤𝑟
4≤𝑟
si 1 m
i0
n
si n m
i0
n
si m n
i0
9. BANKER’S ALGORITHM
• Banker’s Algorithm is a deadlock avoidance strategy.
• It is called so because it is used in banking systems to decide whether a loan can be
granted or not.
Banker’s Algorithm requires-
Whenever a new process is created, it specifies the maximum number of instances of each
resource type that it exactly needs.
• Banker’s Algorithm is executed whenever any process puts forward the request for
allocating the resources.
Safe and Unsafe States
The resource allocation state of a system can be defined by the instances of available and
allocated resources, and the maximum instance of the resources demanded by the processes.
A state of the system is called safe if the system can allocate all the resources requested by
all the processes without entering into deadlock.
If the system cannot fulfil the request of all processes, then the state of the system is called
unsafe.
X Y Z X Y Z
P0 0 0 1 8 4 3
P1 3 2 0 6 2 0
P2 2 1 1 3 3 3
There are 3 units of type X, 2 units of type Y and 2 units of type Z still available. The system
is currently in safe state. Consider the following independent requests for additional
resources in the current state-
REQ1: P0 requests 0 units of X, 0 units of Y and 2 units of Z
REQ2: P1 requests 2 units of X, 0 units of Y and 0 units of Z
Which of the following is TRUE?
1. Only REQ1 can be permitted
2. Only REQ2 can be permitted
3. Both REQ1 and REQ2 can be permitted
4. Neither REQ1 nor REQ2 can be permitted
Solution-
According to question,
Available = [ X Y Z] = [3 2 2]
Now,
Need = Max – Allocation
So, we have-
Allocatio
Max Need
n
X Y Z X Y Z X Y Z
P0 0 0 1 8 4 3 8 4 2
P1 3 2 0 6 2 0 3 0 0
P2 2 1 1 3 3 3 1 2 2
X Y Z X Y Z X Y Z
P0 0 0 3 8 4 3 8 4 0
P1 3 2 0 6 2 0 3 0 0
P2 2 1 1 3 3 3 1 2 2
Available
= [3 2 2] – [0 0 2]
= [3 2 0]
• Now, it follows the safety algorithm to check whether this resulting state is a safe state or
not.
• If it is a safe state, then REQ1 can be permitted otherwise not.
Step-01:
• With the instances available currently, only the requirement of the process P1 can be
satisfied.
• So, process P1 is allocated the requested resources.
• It completes its execution and then free up the instances of resources held by
it. Then-
Available
= [3 2 0] + [3 2 0]
= [6 4 0]
Now,
• It is not possible to entertain any process.
• The system has entered the deadlock state which is an unsafe state.
• Thus, REQ1 will not be permitted.
Checking Whether REQ2 Can Be Entertained-
• Need of P1 = [2 0 0]
• Available = [3 2 2]
Clearly,
• With the instances available currently, the requirement of REQ1 can be satisfied.
• So, banker’s algorithm assumes the request REQ2 is entertained.
• It then modifies its data structures as-
Allocatio
Max Need
n
X Y Z X Y Z X Y Z
P0 0 0 1 8 4 3 8 4 2
P1 5 2 0 6 2 0 1 0 0
P2 2 1 1 3 3 3 1 2 2
Available
= [3 2 2] – [2 0 0]
= [1 2 2]
• Now, it follows the safety algorithm to check whether this resulting state is a safe state or
not.
• If it is a safe state, then REQ2 can be permitted otherwise not.
Step-01:
• With the instances available currently, only the requirement of the process P1 can be satisfied.
• So, process P1 is allocated the requested resources.
• It completes its execution and then free up the instances of resources held by
it. Then-
Available
= [1 2 2] + [5 2 0]
= [6 4 2]
Step-02:
• With the instances available currently, only the requirement of the process P2 can be satisfied.
• So, process P2 is allocated the requested resources.
• It completes its execution and then free up the instances of resources held by it.
Then-
Available
= [6 4 2] + [2 1 1]
= [8 5 3]
Step-03:
• With the instances available currently, the requirement of the process P0 can be satisfied.
• So, process P0 is allocated the requested resources.
• It completes its execution and then free up the instances of resources held by
it. Then-
Available
= [8 5 3] + [0 0 1]
= [8 5 4]
Thus,
• There exists a safe sequence P1, P2, P0 in which all the processes can be executed.
• So, the system is in a safe state.
• Thus, REQ2 can be
permitted. Thus, Correct
Resource Allocation Graph (RAG) is a graph that represents the state of a system pictorially.
Components Of RAG-
There are two major components of a Resource Allocation Graph-
1. Vertices
2. Edges
Vertices-
There are following types of vertices in a Resource Allocation Graph-
1. Process Vertices
2. Resource Vertices
Process Vertices-
• Process vertices represent the processes.
• They are drawn as a circle by mentioning the name of process inside the circle.
Resource Vertices-
• Resource vertices represent the resources.
• Depending on the number of instances that exists in the system, resource vertices may be
single instance or multiple instances.
• They are drawn as a rectangle by mentioning the dots inside the rectangle.
• The number of dots inside the rectangle indicates the number of instances of that resource
existing in the system.
Edges-
There are two types of edges in a Resource Allocation Graph-
1. Assign Edges
2. Request Edges
Assign Edges-
• Assign edges represent the assignment of resources to the processes.
• They are drawn as an arrow where the head of the arrow points to the process and tail of
the process points to the instance of the resource.
Request Edges-
• Request edges represent the waiting state of processes for the resources.
• They are drawn as an arrow where the head of the arrow points to the instance of the resource
and tail of the process points to the process.
• If a process requires ‘n’ instances of a resource type, then ‘n’ assign edges will be drawn.
Example Of RAG-
The following diagram represents a Resource Allocation Graph-
In this approach, The OS doesn't apply any mechanism to avoid or prevent the deadlocks.
Therefore, the system considers that the deadlock will definitely occur. In order to get rid of
deadlocks, The OS periodically checks the system for any deadlock. In case, it finds any of
the deadlock then the OS will recover the system using some recovery techniques.
The main task of the OS is detecting the deadlocks. The OS can detect the deadlocks with the
help of Resource allocation graph.
In order to recover the system from deadlocks, either OS considers resources or processes.
For Resource
• Pre-empt the resource
We can snatch one of the resources from the owner of the resource (process) and give it to
the other process with the expectation that it will complete the execution and will release this
resource sooner. Well, choosing a resource which will be snatched is going to be a bit
difficult.
• Rollback to a safe state
System passes through various states to get into the deadlock state. The operating system
can roll back the system to the previous safe state. For this purpose, OS needs to implement
check pointing at every state.
The moment, we get into deadlock, we will rollback all the allocations to get into the previous
safe state.
For Process
• Kill a process
Killing a process can solve our problem but the bigger concern is to decide which process to
kill. Generally, Operating system kills a process which has done least amount of work until
now.
• Kill all process
This is not a suggestible approach but can be implemented if the problem becomes very serious.
Killing all process will lead to inefficiency in the system because all the processes will execute
again from starting.
Example- Consider the resource allocation graph in the figure-
****