0% found this document useful (0 votes)
200 views70 pages

Process Synchronization in Operating Systems

The document covers key concepts in Operating Systems, particularly focusing on process synchronization, critical sections, and race conditions. It discusses various solutions for managing access to shared resources, including hardware and software methods like Peterson's algorithm and semaphores. Additionally, it addresses deadlocks and classical IPC problems, providing a comprehensive overview of synchronization mechanisms necessary for maintaining data consistency in concurrent processes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
200 views70 pages

Process Synchronization in Operating Systems

The document covers key concepts in Operating Systems, particularly focusing on process synchronization, critical sections, and race conditions. It discusses various solutions for managing access to shared resources, including hardware and software methods like Peterson's algorithm and semaphores. Additionally, it addresses deadlocks and classical IPC problems, providing a comprehensive overview of synchronization mechanisms necessary for maintaining data consistency in concurrent processes.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

R22_CSE( AI&ML ) Operating Systems Notes

Operating Systems

Unit-III
Process Synchronization : Critical Section, Race Conditions, Mutual
Exclusion, Hardware Solution, Peterson’s Solution, The Producer/Consumer
Problem, Semaphores, Monitors,
Classical IPC Problems: Reader’s & Writer Problem, Dinning Philosopher
Problem etc.
Deadlocks: Definition, Necessary and sufficient conditions for Deadlock,
Deadlock Prevention, Deadlock Avoidance: Banker’s algorithm, Deadlock
detection and Recovery.
[Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Objectives Operating Systems Notes

 To present the concept of process synchronization.


 To introduce the critical-section problem, whose solutions can be used to ensure the
consistency of shared data
 To present both software and hardware solutions of the critical-section lem
 To examine several classical process-synchronization problems
 To explore several tools that are used to solve process synchronization problems

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Introduction Operating Systems Notes

 Processes can execute concurrently


 May be interrupted at any time, partially completing execution
 Concurrent access to shared data may result in data inconsistency
 Maintaining data consistency requires mechanisms to ensure the orderly execution of
cooperating processes
Illustration of the problem:
 Suppose that we wanted to provide a solution to the consumer-producer problem that fills all
the buffers.
 We can do so by having an integer counter that keeps track of the number of full buffers.
 Initially, counter is set to 0. It is incremented by the producer after it produces a new buffer
and is decremented by the consumer after it consumes a buffer.

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Process Synchronization Operating Systems Notes

Introduction:
Process Synchronization was introduced to handle problems that arose while multiple process
executions.
Process is categorized into two types on the basis of synchronization and these are given
below:
 Independent Process
 Cooperative Process
Independent Processes
 Two processes are said to be independent if the execution of one process does not affect the
execution of another process.
Cooperative Processes
 Two processes are said to be cooperative if the execution of one process affects the
execution of another process. These processes need to be synchronized so that the order of
execution can be guaranteed. [Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Process Synchronization Operating Systems Notes

Process Synchronization
• It is the task phenomenon of coordinating the execution of processes in such a way that no
two processes can have access to the same shared data and resources.
• It is a procedure that is involved in order to preserve the appropriate order of execution of
cooperative processes.
• In order to synchronize the processes, there are various synchronization mechanisms.
• Process Synchronization is mainly needed in a multi-process system when multiple
processes are running together, and more than one processes try to gain access to the same
shared resource or any data at the same time.

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Producer Operating Systems Notes

while (true) {
/* produce an item in next produced */

while (counter == BUFFER_SIZE) ;


/* do nothing */
buffer[in] = next_produced;
in = (in + 1) % BUFFER_SIZE;
counter++;
}

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Consumer Operating Systems Notes

while (true) {
while (counter == 0) ; /* do nothing */
next_consumed = buffer[out];
out = (out + 1) % BUFFER_SIZE;
counter--;
/* consume the Item in next consumed */
}

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Race Condition Operating Systems Notes

 A race condition is a situation, where several processes access and manipulate the same data concurrently and
the outcome of execution depends on the particular order in which the access takes place is called a race
condition.
 When more than one processes are 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 known as a 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.
 A race condition is a situation that may occur inside a critical section.
 This happens when the result of multiple thread execution in the critical section differs according to the order
in which the threads execute.
 Race conditions in critical sections can be avoided if the critical section is treated as an atomic instruction.
Also, proper thread synchronization using locks or atomic variables can prevent race conditions.
 To guard against the race condition, we need to ensure one process at a time can be manipulating the variable
counter.
 To make such a guarantee, we require that the processes be synchronized in some way.

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Race Condition Operating Systems Notes

• counter++ could be implemented as

register1 = counter
register1 = register1 + 1
counter = register1
• counter-- could be implemented as

register2 = counter
register2 = register2 - 1
counter = register2

• Consider this execution interleaving with “count = 5” initially:


S0: producer execute register1 = counter {register1 = 5}
S1: producer execute register1 = register1 + 1 {register1 = 6}
S2: consumer execute register2 = counter {register2 = 5}
S3: consumer execute register2 = register2 – 1 {register2 = 4}
S4: producer execute counter = register1 {counter = 6 }
S5: consumer execute counter = register2 {counter = 4}
[Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Critical Section Problem Operating Systems Notes

 A section of code, common to n cooperating processes, in which the processes may be accessing common
variables.
 Consider system of n processes {p0, p1, … pn-1}
 Each process has critical section segment of code
 Process may be changing common variables, updating table, writing file, etc
 When one process in critical section, no other may be in its critical section

 A Critical Section problem is to design a protocol that the processes can use to cooperate.

 Entry Section Code requesting entry into the critical section.

 Exit Section The end of the critical section, releasing or allowing others in.

 Remainder Section Rest of the code AFTER the exit section.

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Critical Section Operating Systems Notes

• General structure of process Pi

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Algorithm for Process Pi Operating Systems Notes

do {

while (turn == j);


critical section
turn = j;
remainder section
} while (true);

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Solution to Critical-Section Problem Operating Systems Notes

 Mutual Exclusion - If process Pi is executing in its critical section, then no other


processes can be executing in their critical sections
 Progress - If no process is executing in its critical section and there exist some
processes that wish to enter their critical section, then the selection of the
processes that will enter the critical section next cannot be postponed
indefinitely
 Bounded Waiting - A bound must exist on the number of times that other
processes are allowed to enter their critical sections after a process has made
a request to enter its critical section and before that request is granted
 Assume that each process executes at a nonzero speed
 No assumption concerning relative speed of the n processes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Critical-Section Handling in OS Operating Systems Notes

Two approaches depending on if kernel is preemptive or non- preemptive


 Preemptive – allows preemption of process when running in kernel mode
 Non-preemptive – runs until exits kernel mode, blocks, or voluntarily
yields CPU
Essentially free of race conditions in kernel mode

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
Software Based Solution to Critical Section Problem
R22_CSE( AI&ML ) Operating Systems Notes

Peterson’s Solution[Peterson’s Algorithm]


 Peterson's algorithm (or Peterson's solution) is a concurrent
programming algorithm for mutual exclusion that allows two processes to share
a single-use resource without conflict, using only shared memory
for communication.
 It was formulated by Gary L. Peterson in 1981.
 While Peterson's original formulation worked with only two processes.

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Peterson’s Solution Operating Systems Notes

 Two process solution


 Assume that the LOAD and STORE instructions are atomic; that is, cannot be
interrupted.
 The two processes share two variables:
 int turn; [1 and 0] P0, P1
 Boolean flag[2] [TRUE, FALSE]
 The variable turn indicates whose turn it is to enter the critical section.
 The flag array is used to indicate if a process is ready to enter the critical
section. flag[i] = true implies that process Pi is ready!

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Algorithm for Process Pi Operating Systems Notes

do {
flag[i] = TRUE;
turn = j;
while ( flag[j] && turn = j);

CRITICAL SECTION

flag[i] = FALSE;

REMAINDER SECTION

} while (TRUE);

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
Code for Process P0
R22_CSE( AI&ML )
Code for Process P1 Operating Systems Notes

flag[0] = TRUE; flag[1] = TRUE;


turn = 1; turn = 0;
while ( flag[1]==true && turn == 1); while ( flag[0]==true && turn == 0);

CRITICAL SECTION CRITICAL SECTION

flag[0] = FALSE; flag[1] = FALSE;

REMAINDER SECTION REMAINDER SECTION

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Peterson’s Solution Operating Systems Notes

Peterson’s Solution preserves all three conditions :

 Mutual Exclusion is assured as only one process can access the critical section at any time.
 Progress is also assured, as a process outside the critical section does not block other
processes from entering the critical section.
 Bounded Waiting is preserved as every process gets a fair chance.

Disadvantages of Peterson’s Solution

 It involves Busy waiting


 It is limited to 2 processes.

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
Hardware Based Solution to Critical Section Problem
R22_CSE( AI&ML ) Operating Systems Notes

 Problems of Critical Section are also solvable by hardware.


 Uni-processor systems disables interrupts while a Process Pi is using the CS but it is a great
disadvantage in multiprocessor systems.
 Some systems provide a lock functionality where a Process acquires a lock while entering
the CS and releases the lock after leaving it.
 Thus another process trying to enter CS cannot enter as the entry is locked. It can only do so
if it is free by acquiring the lock itself.
 Another advanced approach is the Atomic Instructions (Non- Interruptible instructions).
Hardware Based Solutions:
 TestAndSet
 Swap

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
Hardware Based Solution to Critical Section Problem
R22_CSE( AI&ML ) Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
TestAndSet Instruction Operating Systems Notes

 Definition:

boolean TestAndSet (boolean *target)


{
boolean rv = *target;
*target = TRUE;
return rv:
}
Executed atomically
Returns the original value of passed parameter
Set the new value of passed parameter to “TRUE”. [Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Solution using TestAndSet Operating Systems Notes

 Shared boolean variable lock., initialized to false.


 Solution:
do {
while ( TestAndSet (&lock ))
; /* do nothing

// critical section

lock = FALSE;

// remainder section

} while ( TRUE);

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Swap Instruction Operating Systems Notes

• Definition:

void Swap (boolean *a, boolean *b)


{
boolean temp = *a;
*a = *b;
*b = temp:
}

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML ) Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Semaphore Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Process Definition Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Process Definition Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Semaphore as General Synchronization Tool Operating Systems Notes

 Provides mutual exclusion


– Semaphore S; // initialized to 1
– wait (S);
Critical Section
signal (S);

Two operations:
block – place the process invoking the operation on the appropriate waiting queue
wakeup – remove one of processes in the waiting queue and place it in the ready
queue

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
Semaphore Implementation with no Busy waiting
R22_CSE( AI&ML ) Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Process Definition Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Monitors Operating Systems Notes

• A high-level abstraction that provides a convenient and effective mechanism for process
synchronization
• Abstract data type, internal variables only accessible by code within the procedure
• Only one process may be active within the monitor at a time
• But not powerful enough to model some synchronization schemes

monitor monitor-name
{
// shared variable declarations
procedure P1 (…) { …. }

procedure Pn (…) {……}

Initialization code (…) { … }


}
}
[Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Monitors Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Monitors in Producer-Consumer Problem Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Classical IPC Problems Operating Systems Notes

 Classical problems used to test newly-proposed synchronization


schemes
 Bounded-Buffer Problem
 Readers and Writers Problem
 Dining-Philosophers Problem

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Bounded-Buffer Problem Operating Systems Notes

 n buffers, each can hold one item


 Semaphore mutex initialized to the value 1
 Semaphore full initialized to the value 0
 Semaphore empty initialized to the value n

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Bounded-Buffer Problem Operating Systems Notes

The structure of the producer process The structure of the consumer process

do { do {
... wait(full);
/* produce an item in next_produced */ wait(mutex);
... ...
/* remove an item from buffer to next_consumed */
wait(empty); ...
wait(mutex); signal(mutex);
... signal(empty);
/* add next produced to the buffer */ ...
... /* consume the item in next consumed */
signal(mutex); ...
signal(full); } while (true);
} while (true);

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Bounded-Buffer Problem Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Readers-Writers Problem Operating Systems Notes

 A data set is shared among a number of concurrent processes


 Readers – only read the data set; they do not perform any updates
 Writers – can both read and write
 Problem –
 Allow multiple readers to read at the same time
 Only one single writer can access the shared data at the same time
 Several variations of how readers and writers are considered – all involve some form of
priorities
 Shared Data
 Data set
 Semaphore wr_mutex initialized to 1
 Semaphore mutex initialized to 1
 Integer read_count initialized to 0
[Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Readers-Writers Problem Operating Systems Notes

• The structure of a writer process The structure of a reader process


do {
wait(mutex);
do { read_count++;
wait(wr_mutex); if (read_count == 1)
... wait(wr_mutex);
/* writing is performed */ signal(mutex);
... ...
signal(wr_mutex); /* reading is performed */
...
} while (true);
wait(mutex);
read count--;
if (read_count == 0)
signal(wr_mutex);
signal(mutex);
} while (true);

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Readers-Writers Problem Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Dining-Philosophers Problem Operating Systems Notes

 Philosophers spend their lives alternating thinking and eating


 Don’t interact with their neighbors, occasionally try to pick up 2 chopsticks (one at a time) to eat from bowl
 Need both to eat, then release both when done
 In the case of 5 philosophers
 Shared data
 Bowl of rice (data set)
 Semaphore chopstick [5] initialized to 1

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Dining-Philosophers Problem Operating Systems Notes

• The structure of Philosopher i:


do {
wait (chopstick[i] );
wait (chopStick[ (i + 1) % 5] );

// eat

signal (chopstick[i] );
signal (chopstick[ (i + 1) % 5] );

// think

} while (TRUE);

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Deadlock Operating Systems Notes

 A deadlock is a situation in which two computer process sharing the same resource are effectively preventing
each other from accessing the resource, resulting in both process to waiting state.
System Model
 System consists of resources
 Resource types R1, R2, . . ., Rm
 CPU cycles, memory space, I/O devices
 Each resource type Ri has Wi instances.
 Each process utilizes a resource as follows:
 request
 use
 release

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Deadlock Characterization Operating Systems Notes

Deadlock can arise if four conditions hold simultaneously.


 Mutual exclusion: only one process at a time can use a resource

 Hold and wait: a process holding at least one resource is waiting to acquire
additional resources held by other processes

 No preemption: a resource can be released only voluntarily by the process


holding it, after that process has completed its task

 Circular wait: there exists a set {P0, P1, …, Pn} of waiting processes such
that P0 is waiting for a resource that is held by P1, P1 is waiting for a resource
that is held by P2, …, Pn–1 is waiting for a resource that is held by Pn, and Pn is
waiting for a resource that is held by P0.
[Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Resource-Allocation Graph Operating Systems Notes

•A set of vertices V and a set of edges E.

⚫ V is partitioned into two types:


⚫ P = {P1, P2, …, Pn}, the set consisting of all the processes in
the system

⚫ R = {R1, R2, …, Rm}, the set consisting of all resource types in the
system

⚫ request edge – directed edge Pi  Rj


⚫ assignment edge – directed edge Rj  Pi

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Resource-Allocation Graph Operating Systems Notes

⚫ Proce Basic Facts


ss
⚫ If graph contains no cycles
 no deadlock
⚫ Resource Type with 4
⚫ If graph contains a cycle 
instances
⚫ if only one instance per
resource type,
then deadlock
⚫ Pi requests instance
Pi of Rj ⚫ if several instances per resource
Rj
type, possibility of deadlock
⚫ Pi is holding an instance
of Rj Pi
Rj

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Example of a Resource Allocation Graph Operating Systems Notes

Resource Allocation Graph with cycle but no


Deadlock

Resource Allocation Graph With A Deadlock


Resource Allocation Graph with
no Deadlock
[Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Methods for Handling Deadlocks Operating Systems Notes

⚫ Ensure that the system will never enter a deadlock state:


⚫ Deadlock Ignorance
⚫ Deadlock Prevention
⚫ Deadlock Avoidance
⚫ Deadlock Detection & Recovry
⚫ Allow the system to enter a deadlock state and then recover
⚫ Ignore the problem and pretend that deadlocks never occur in the
system; used by most operating systems, including UNIX
Deadlock No Deadlock

bridge
bridge
City A City B City A City B

[Link] Rao, Assistant Professor


river river E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Deadlock Prevention Operating Systems Notes

•Restrain the ways request can be made

⚫ Mutual Exclusion – not required for sharable resources (e.g., read-only


files); must hold for non-sharable resources
⚫ Hold and Wait – must guarantee that whenever a process requests
a resource, it does not hold any other resources
⚫ Require process to request and be allocated all its resources before it
begins execution, or allow process to request resources only when the
process has none allocated to it.
⚫ Low resource utilization; starvation possible
⚫ No Preemption –
⚫ If a process that is holding some resources requests another resource that
cannot be immediately allocated to it, then all resources currently being
held are released
⚫ Preempted resources are added to the list of resources for which the
process is waiting
⚫ Process will be restarted only when it can regain its old resources, as well as
the new ones that it is requesting [Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.

R22_CSE( AI&ML )
Deadlock Avoidance Operating Systems Notes

Requires that the system has some additional a priori information


available
 Simplest and most useful model requires that each process declare the maximum
number of resources of each type that it may need
 The deadlock-avoidance algorithm dynamically examines the resource-allocation state to
ensure that there can never be a circular-wait condition
 Resource-allocation state is defined by the number of available and allocated resources,
and the maximum demands of the processes
Basic Facts
 If a system is in safe state  no deadlocks
 If a system is in unsafe state  possibility of deadlock
 Avoidance  ensure that a system will never enter an unsafe state.

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Deadlock Avoidance Operating Systems Notes

Safe State
 When a process requests an available resource, system must decide if
immediate allocation leaves the system in a safe state
 System is in safe state if there exists a sequence <P1, P2, …, Pn> of ALL
the processes in the systems such that for each Pi, the resources
that Pi can still request can be satisfied by currently available resources
+ resources held by all the Pj, with j < I
 That is:
 If Pi resource needs are not immediately available, then Pi can wait until all Pj
have finished
 When Pj is finished, Pi can obtain needed resources, execute, return allocated
resources, and terminate
 When Pi terminates, Pi +1 can obtain its needed resources, and so on

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Deadlock Avoidance Algorithm Operating Systems Notes

 Single instance of a resource type


 Use a resource-allocation graph

 Multiple instances of a resource type


 Use the banker’s algorithm

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Resource-Allocation Graph Algorithm Operating Systems Notes

 Claim edge Pi -> Rj indicated that process Pj may request resource Rj; represented by a dashed line
 Claim edge converts to request edge when a process requests a resource
 Request edge converted to an assignment edge when the resource is allocated to the process
 When a resource is released by a process, assignment edge reconverts to a claim edge
 Resources must be claimed a priori in the system
 Suppose that process Pi requests a resource Rj
 The request can be granted only if converting the request edge to an assignment edge does not result in the
formation of a cycle in the resource allocation graph.
Safe State In Resource-Allocation Graph Unsafe State In Resource-Allocation Graph

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Safety Algorithm Operating Systems Notes

1. Let Work and Finish be vectors of length m and n, respectively. Initialize:


Work = Available
Finish [i] = false for i = 0, 1, …, n- 1

2. Find an i such that both:


(a) Finish [i] = false
(b) Needi  Work
If no such i exists, go to step 4
3. Work = Work + Allocationi
Finish[i] = true
go to step 2
4. If Finish [i] == true for all i, then the system is in a safe state

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Resource-Request Algorithm for Process Pi Operating Systems Notes

Requesti = request vector for process Pi. If Requesti [j] = k then process
Pi wants k instances of resource type Rj
[Link] Requesti  Needi go to step 2. Otherwise, raise error condition, since
process has exceeded its maximum claim
[Link] Requesti  Available, go to step 3. Otherwise Pi must wait, since
resources are not available
[Link] to allocate requested resources to Pi by modifying the state as
follows:
Available = Available – Requesti;
Allocationi = Allocationi + Requesti;
Needi = Needi – Requesti;
 If safe  the resources are allocated to P
i
 If unsafe  P must wait, and the old resource-allocation state is restored
[Link] Rao, Assistant Professor
i
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Banker’s Algorithm Operating Systems Notes

 Multiple instances
 Each process must a priori claim maximum use
 When a process requests a resource it may have to wait
 When a process gets all its resources it must return them in a finite amount of time
Let n = number of processes, and m = number of resources types.

 Available: Vector of length m. If available [j] = k, there are k instances of resource type Rj available

 Max: n x m matrix. If Max [i,j] = k, then process Pi, may request at most k instances of resource type Rj

 Allocation: n x m matrix. If Allocation[i,j] = k then Pi is currently allocated k instances of Rj


 Need: n x m matrix. If Need[i,j] = k, then Pi may need k more instances of Rj to complete its task

Need [i,j] = Max[i,j] – Allocation [i,j]

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Banker’s Algorithm Example Operating Systems Notes

⚫ 5 processes P0 through P4;


⚫ 3 resource types:
A (10 instances), B (5instances), and C (7 instances)
⚫ Snapshot at time T0:
Allocation Max Available Need

Process ABC ABC ABC ABC


P0 010 753 332 743
P1 200 322 122
P2 302 902 600
P3 211 222 011
P4 002 433 431
= 725
The system is in a safe state since the sequence < P1, P3, P4, P2, P0> satisfies safety criteria [Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML ) Operating Systems Notes
Example: P1 Request (1,0,2)
 Check that Request  Available (that is, (1,0,2)  (3,3,2)  true
Allocation Max Available Need
Process ABC ABC ABC ABC
P0 010 753 332 743
P1 200 322 122
P2 302 902 600
P3 211 222 011
P4 002 433 431
= 725
 Executing safety algorithm shows that sequence < P1, P3, P4, P0, P2> satisfies safety
requirement
 Can request for (3,3,0) by P4 be granted?
 Can request for (0,2,0) by P0 be granted? [Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML ) Deadlock Detection Operating Systems Notes

 Single instance of a resource type


 Use a resource-allocation graph for finding Wait-for
graph

 Multiple instances of a resource type


 Use the banker’s algorithm

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Single Instance of Each Resource Type Operating Systems Notes

• Maintain wait-for graph


– Nodes are processes
– Pi  Pj if Pi is waiting for Pj

• Periodically invoke an algorithm that searches for a cycle in the


graph. If there is a cycle, there exists a deadlock

• An algorithm to detect a cycle in a graph requires an order of n2


operations, where n is the number of vertices in the graph

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Process Definition Operating Systems Notes

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML ) Operating Systems Notes
Resource-Allocation Graph and Wait-for Graph
R1

P2
P1 P3

R2 P4 R3

Resource-Allocation Graph

P2

P1 P3 Resource-Allocation Graph Corresponding wait-for graph

P4
[Link] Rao, Assistant Professor
Corresponding wait-for graph E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Several Instances of a Resource Type Operating Systems Notes

• 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 m matrix indicates the current request of each process. If Request [i][j] = k, then process Pi
is requesting k more instances of resource type Rj.

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Detection Algorithm Operating Systems Notes

1. Let Work and Finish be vectors of length m and n, respectively Initialize:


(a) Work = Available
(b) For i = 1,2, …, n, if Allocationi  0, then
Finish[i] = false; otherwise, Finish[i] = true

2. Find an index i such that both:


(a) Finish[i] == false
(b) Requesti  Work

If no such i exists, go to step 4

3. Work = Work + Allocationi


Finish[i] = true
go to step 2

4. If Finish[i] == false, for some i, 1  i  n, then the system is in deadlock state. Moreover, if Finish[i] == false, then Pi is
deadlocked

Note: Algorithm requires an order of O(m x n2) operations to detect whether the system is in deadlocked state
[Link] Rao, Assistant Professor
E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML )
Example-1 of Detection Algorithm Operating Systems Notes

• Five processes P0 through P4; three resource types


A (7 instances), B (2 instances), and C (6 instances)

• Snapshot at time T0:


Allocation Request Available
Process ABC ABC ABC
P0 010 000 000
P1 200 202
P2 303 000
P3 211 100
P4 002 002

• Sequence <P0, P2, P3, P1, P4> will result in Finish[i] = true for all i

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML ) Example-2 of Detection Algorithm Operating Systems Notes

• P2 requests an additional instance of type C

Allocation Request Available


Process ABC ABC ABC
P0 010 000 000
P1 200 202
P2 303 001
P3 211 100
P4 002 002

• State of system?
– Can reclaim resources held by process P0, but insufficient resources to fulfill other processes; requests
– Deadlock exists, consisting of processes P1, P2, P3, and P4

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
R22_CSE( AI&ML ) Recovery from Deadlock: Process Termination Operating Systems Notes

 Abort all deadlocked processes

 Abort one process at a time until the deadlock cycle is eliminated

 In which order should we choose to abort?


 Priority of the process
 How long process has computed, and how much longer to completion
 Resources the process has used
 Resources process needs to complete
 How many processes will need to be terminated
 Is process interactive or batch?

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
Recovery from Deadlock: Resource Preemption
R22_CSE( AI&ML ) Operating Systems Notes

 Selecting a victim – minimize cost

 Rollback – return to some safe state, restart process for that state

 Starvation – same process may always be picked as victim, include number of rollback in
cost factor

[Link] Rao, Assistant Professor


E. Kiran Kumar, [Link](CSE), GNITC.
Any Doubts?
R22_CSE( AI&ML ) Operating Systems Notes

[Link] Rao, Assistant Professor

You might also like