0% found this document useful (0 votes)
8 views46 pages

OS Module 3 CEC

Uploaded by

garakriska
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)
8 views46 pages

OS Module 3 CEC

Uploaded by

garakriska
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
You are on page 1/ 46

OPERATING SYSTEMS MODULE 3

SYNCHRONIZATION
What is synchronization?
Synchronization is the method which ensures the orderly execution of cooperating processes that
share logical address space (ie: code and data) or share data through files or messages through
threads so that data consistency is maintained.
The concurrent-access to shared-data may result in data-inconsistency. To maintain data-
consistency: the orderly execution of co-operating processes is necessary.
Suppose that we wanted to provide a solution to producer-consumer problem that fills
all full buffers. We can do so by having a variable counter that keeps track of the no. of
full buffers
Initially, counter=0.
 counter is incremented by the producer after it produces a new item to buffer.
 counter is decremented by the consumer after it consumes an item from buffer.
Shared-data:

Dept. of CSE, CEC, Mangaluru Page 1


OPERATING SYSTEMS MODULE 3

Producer Process: Consumer Process:

What is Race condition?


In multiprogramming environment, a situation where several cooperative processes access
& manipulate same data (shared data) concurrently and the outcome of the execution
depends on particular order in which the access takes place, is called a race condition.
Example: In Producer-consumer process if the count++ and count== is executed in the following
order, resulting in race condition.
counter++ could be implemented as: counter- - may be implemented as:

Consider this execution interleaving with counter = 5 initially: The value of counter may be either
4 or 6, where the correct result should be 5. This is an example for race condition. To prevent
race conditions, concurrent-processes must be synchronized.

Dept. of CSE, CEC, Mangaluru Page 2


OPERATING SYSTEMS MODULE 3

2.10 CRITICAL-SECTION PROBLEM


What is critical section? Explain the requirements to be satisfied for critical section problem
Critical-section is a segment-of-code in which a process may be changing common (shared)
variables or updating a table or writing a file. Each process has a critical-section in which the
shared-data is accessed.
General structure of a typical process has following:
1) Entry-section
 Requests permission to enter the critical-section.
2) Critical-section
 Mutually exclusive in time i.e. no other process can execute in its critical-section.
3) Exit-section
 Follows the critical-section.
4) Remainder-section

General structure of a typical process

The 3 requirements to be satisfied for critical section problem is


1. Mutual Exclusion: If process Pi is executing in its critical section, then no other processes can
be executing in their critical sections.
2. 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.
3. Bounded Waiting: There must be a bound 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 the request is granted.

Dept. of CSE, CEC, Mangaluru Page 3


OPERATING SYSTEMS MODULE 3

2.11 PETERSON’S SOLUTION FOR CRITICAL SECTION PROBLEM

Illustrate with examples the Peterson’s solution for critical section problem and prove that
mutual exclusion property is preserved.

OR

Discuss an efficient algorithm which can meet all the requirements to solve the critical
section problem.

Peterson’s Solution is a classic software-based solution to the critical-section problem. This is


limited to 2 processes. The 2 processes alternate execution between critical-sections and
remainder-sections. The two processes share 2 variables:

Where variable turn indicates whose turn is to enter its critical-section. i.e., if turn== i, then
process Pi is allowed to execute in its critical-section. The flag array is used to indicate if a
process is ready (interested) to enter its critical-section. i.e. if flag[i]=true, then Pi is ready to enter
its critical-section.
while (true)
{
flag[i] = TRUE;
turn = j;
while ( flag[j] && turn == j);
CRITICAL SECTION
flag[i] = FALSE;
REMAINDER SECTION
}

The structure of process Pi in Peterson‘s solution

To prove Mutual exclusion property, let us consider two processes Pi = P0 and Pj = P1: we note
that process Pi (P0) enters its critical section only if either flag[j] = = flag[1]= = false or turn = = i
= 0 ( P1 is not interested or next turn to enter CS is P0)
If both processes can be executing in their critical sections at the same time, then flag[0] = =
flag[1] = = true.

Dept. of CSE, CEC, Mangaluru Page 4


OPERATING SYSTEMS MODULE 3

These two observations imply that P0 and P1 could not have successfully executed their while
statements at about the same time, since the value of turn can be either 0 or 1 but cannot be both.
Hence one of the process say Pi (P0) must have successfully executed the while statement and
enters into critical section. Whereas Pj (P1) has to execute at least one additional statement turn =
= i (0). However, since at that time, falg[i] = flag[0] =true, and turn = = i (0), this condition(P1 is
in trap state) will persist as long as P0 is in critical section. Thus Mutual Exclusion is preserved.
To prove Progress and bounded wait property, let us consider two processes Pi = P0 and Pj = P1

2.12 SYNCHRONIZATION HARDWARE (Hardware based Solution for Critical-section


Problem)
Explain synchronization hardware.
Software based solution to critical section problem such as Peterson’s solution is not guaranteed
to work. We can protect critical regions via locks. Race conditions are prevented by acquiring
lock. Critical section problem could be solved simply in a uni-processor environment by disabling
interrupts. Disabling interrupt on a multiprocessor system is time consuming. Many modern
computer systems therefore provide a special hardware instructions that allow test and modify the
content of a word atomically. The instructions are TestAndSet() and swap()
Describe n-process solution to critical section problem which uses test and set() hardware
instruction. Prove how this algorithm satisfies all the requirements of critical section
problem’s solution.
A lock is a simple tool used to solve the critical-section problem. Race conditions are prevented
by following restriction. A process must acquire a lock before entering a critical-section. The
process releases the lock when it exits the critical-section.

Dept. of CSE, CEC, Mangaluru Page 5


OPERATING SYSTEMS MODULE 3

TestAndSet( ): instruction is used to test & modify the content of a word atomically. An atomic-
operation is an operation that completes in its entirety without interruption.
The definition of TestAndSet( ) is:
boolean TestAndSet (boolean *target)
{
boolean rv = *target;
*target = TRUE;
return rv:
}

To prove Mutual Exclusion with TestAndSet() is as follows:


Initially shared boolean variable lock is initialized to false.
while (true)

while ( TestAndSet (&lock )) ; // entry section code

Critical Section

lock = FALSE; //exit section code

// remainder section
}
Suppose P0 is the process interested to enter CS. Initially lock =false, so that while(TestAndSet
(&lock )) statement results in false. P0 enters CS. When P0 is inside CS, P1 attempts to enter CS,
but P1 is blocked in the entry section of CS itself, since the value of lock = true.
SWAP( )
Definition of Swap( ) is as follows:
void swap (boolean *a, boolean *b)
{
boolean temp = *a;
*a = *b;
*b = temp:
}
This instruction is executed atomically. If the machine supports the Swap(), then mutual-

Dept. of CSE, CEC, Mangaluru Page 6


OPERATING SYSTEMS MODULE 3

exclusion can be provided as follows:


1) A global boolean variable lock is declared and is initialized to false.
2) In addition, each process has a local Boolean variable key
To prove Mutual Exclusion with Swap() is as follows
Shared Boolean variable lock initialized to FALSE; Each process has a local Boolean variable
key.
while (true)
{
key = TRUE;
while ( key == TRUE)

Swap (&lock, &key );


Critical Section
lock = FALSE;
Remainder
section
}
2.13 SEMAPHORES
• The hardware solution to the critical section problem is complicated for application
programmers to use
• To overcome this difficulty we use synchronization tool called semaphore
• Semaphore S – integer variable apart from initialization it can be accessed and modified
only by two operations wait() and signal()
What are semaphores?List any 3 application of semaphores
Semaphore is an integer variable, which is used in mutual exclusive manner by various concurrent
cooperative processes in order to achieve synchronization.
Apart from semaphores initialization it can be accessed and modified only by two operations
wait() and signal().
Application of Semaphore
1. Semaphore is used to solve critical section problem
2. Semaphore is used to decide the order of execution among the processes.(synchronization)
3. Resource management

Dept. of CSE, CEC, Mangaluru Page 7


OPERATING SYSTEMS MODULE 3

Definition of wait() and signal()


wait (S)
{
while (S <= 0); // no-op
S--;
}
signal (S)
{
S++;
}
TYPES OF SEMAPHORES
Explain binary and counting semaphores with examples.
1. Counting semaphore
2. Binary semaphore

Explain the usage of semaphores.


Counting Semaphore
Explain how semaphore is used to handle resource management.
Handling Resource management
It is mainly used in resource management. The value of a counting semaphore can range over an
unrestricted domain. Counting semaphores can be used to control access to a given resource
consisting of finite number of instances. The semaphore is initialized to the number of resources
available. Each process that wishes to use a resource performs a wait() operation on the
semaphore (thereby decrementing the count). When a process releases a resource, it performs a
signal() operation (incrementing the count). When the count for the semaphore goes to 0, all
resources are being used. After that, processes that wish to use a resource will block until the
count becomes greater than 0.
Binary Semaphore
The value of a semaphore can range only between 0 and 1.
On some systems, binary semaphores are known as mutex locks, as they are locks that provide
mutual-exclusion

Dept. of CSE, CEC, Mangaluru Page 8


OPERATING SYSTEMS MODULE 3

Solving Critical-section Problem using Binary Semaphores


Explain how semaphore is used to solve critical section problem
Binary semaphores can be used to solve the critical-section problem for multiple processes.

Mutual-exclusion implementation with semaphores


The ‘n’ processes share semaphore Mutex which is initialized to 1
Explanation: Whichever the process interested to enter critical section, say P1 must execute the
wait (mutex) at its entry section. Mutex is decremented by 1, if its value is > 0 and process P1
enters into CS. Now the Mutex value = 0. When P1 is inside the CS, if P2 attempts to enter CS by
executing wait (mutex). Since the mutex value is 0, the while (mutex<=0) statement results in true
and blocks process P1 in entry section. Thus the mutual exclusion property is ensured.
Explain how semaphore is used to solve synchronization problem
Solving Synchronization Problems
Semaphores can also be used to solve synchronization problems.
For example, consider 2 concurrently running-processes: P1 with a statement S1 and P2 with a
statement S2. Suppose we require that S2 be executed only after S1 has completed. We can
implement this scheme readily by letting P1 and P2 to share a common semaphore synch
initialized to 0, and by inserting the following statements in process P1
S1:
signal(synch)
and the following statements in process P2
wait(synch)
S2;
Since synch is initialized to 0, P2 will execute S2 only after P1 has invoked signal (synch), which
is after statement S1 has been executed.

Dept. of CSE, CEC, Mangaluru Page 9


OPERATING SYSTEMS MODULE 3

Advantages of semaphore
What are the advantages of semaphore?
1. Semaphores allow only one process into the critical section.
2. Semaphores follow mutual exclusion principle strictly.
3. Semaphores are much more efficient than some other methods of synchronization
SEMAPHORE IMPLEMENTATION
The main disadvantage of semaphore is Busy waiting.
What is busy waiting in critical section concept?
OR
What is spinlock?
While a process is in its critical-section, any other process that tries to enter its critical-
section must loop continuously in the entry-code, and this situation in critical section
problem is called busy waiting.
Busy waiting wastes CPU cycles that some other process might be able to useproductively.
This type of semaphore is also called a spinlock (because the process "spins" while waiting
for the lock).
IMPLEMENTATION OF SEMAPHORE
Explain implementation of semaphore
To overcome busy waiting, we can modify the definition of the wait() and signal() as follows:
When a process executes the wait() and finds that the semaphore-value is not positive, it must
wait. However, rather than engaging in busy waiting, the process can blockitself.
A process that is blocked (waiting on a semaphore S) should be restarted when someother process
executes a signal(). The process is restarted by awakeup().
We assume 2 simple operations:
1) block() suspends the process that invokes it.
2) wakeup(P) resumes the execution of a blocked process P.
We define a semaphore as follows:

Dept. of CSE, CEC, Mangaluru Page 10


OPERATING SYSTEMS MODULE 3

Implementation of wait( )
wait (S)
{
value--;
if (value <0)
{
add this process to waiting queue
block();
}
}
Implementation of signal( )
signal(S)
{
value++;
if (value <=0)
{
Remove a process P from the waiting queue
wakeup(P);
}
}

NOTE:
The (critical-section) problem can be solved in two ways:
1) In a uni-processor environment
¤ Inhibit interrupts when the wait and signal operations execute.
¤ Only current process executes, until interrupts are re-enabled & the
scheduler regains control.
2) In a multi-processor environment
¤ Inhibiting interrupts doesn't work.
¤ Use the hardware / software solutions described above.

Dept. of CSE, CEC, Mangaluru Page 11


OPERATING SYSTEMS MODULE 3

DEADLOCKS & STARVATION


Deadlock occurs when 2 or more processes are waiting indefinitely for an event that can be
caused by only one of the waiting processes. The event in question is the execution of a signal()
operation.
To illustrate this, consider 2 processes, Po and P1, each accessing 2 semaphores, S and Q. Let S
and Q be initialized to1.

Suppose that Po executes wait(S) and then P1 executes wait(Q). When Po executes wait(Q), it
must wait until P1 executes signal(Q). Similarly, when P1 executes wait(S), it must wait until Po
executes signal(S). Since these signal() operations cannot be executed, Po & P1 are deadlocked.
Starvation (indefinite blocking) is another problem related to deadlocks.
Starvation is a situation in which processes wait indefinitely within the semaphore. Indefinite
blocking may occur if we remove processes from the list associated with a semaphore in LIFO
(last-in, first-out)order.

2.14 CLASSIC PROBLEMS OF SYNCHRONIZATION


Here we discuss a number of synchronization problems as examples of a large class of
concurrency control problems. These problems are used for testing nearly every newly proposed
synchronization scheme.
1. Bounded-Buffer Problem
2. Readers and Writers Problem
3. Dining-Philosophers Problem

Dept. of CSE, CEC, Mangaluru Page 12


OPERATING SYSTEMS MODULE 3

BOUNDED-BUFFER PROBLEM
Give a solution to the bounded buffer problem using semaphores. Write the structure of
producer and consumer processes
The bounded-buffer problem is related to the producer consumer problem. There is a pool of n
buffers, each capable of holding one item.
Shared data:

 The mutex semaphores provide mutual exclusion for access to the buffer pool and is
initialized to the value 1
 empty and full semaphores are used to count the number of empty and full items in buffer
respectively.
 Initially empty = n; full=0
The symmetry between the producer and the consumer is ensured by the producer producing full
items in buffers for the consumer and the consumer produces empty buffers for the producer.
The structure of the producer process
while (true)
{
// produce an item
wait (empty);
wait (mutex);
// add the item to the buffer
signal (mutex);
signal (full);
}
The structure of the consumer process
while (true)
{
wait (full);
wait (mutex);
// remove an item from buffer
signal (mutex);

Dept. of CSE, CEC, Mangaluru Page 13


OPERATING SYSTEMS MODULE 3

signal (empty);
// consume the removed item
}

READERS WRITERS PROBLEM


*****Explain Readers Writers problem with solution provided by semaphore
In cooperative process a data set is shared among a number of concurrent processes. In readers
arbiters problem:
 Readers are the processes which want to only read the database (DB).
 Writers are the processes which want to update (i.e. to read & write) the DB.

The actual problem in Readers Writers problem is, if 2 readers can access the shared-DB
simultaneously without any problems. However, if a writer & other process (either a reader or a
writer) access the shared-DB simultaneously, problems may arise.
Solution: The writers must have exclusive access to the shared-DB while writing to the DB.

Shared-data

Where,
 mutex is used to ensure mutual-exclusion when the variable readcount is updated.
 wrt is common to both reader and writer processes.
 wrt is used as a mutual-exclusion semaphore for the writers. Also wrt is used by the
first/last reader that enters/exits the critical-section.
 readcount counts the number of processes currently reading the object.

Initialization
mutex = 1, wrt = 1, readcount = 0
The structure of a writer process
while (true)
{
wait (wrt) ;

// writing is performed
signal (wrt) ;
}
Dept. of CSE, CEC, Mangaluru Page 14
OPERATING SYSTEMS MODULE 3

The structure of a reader process


while (true)
{
wait (mutex) ;
readcount ++ ;
if (readcount == 1) then wait (wrt) ;
signal (mutex)
// reading is performed
wait (mutex) ;
readcount - - ;
if (readcount == 0) then signal (wrt) ;
signal (mutex) ;
}

THE DINING-PHILOSOPHERS PROBLEM


Explain Dining Philosophers problem with solution provided by semaphore.
Problem statement:
 There are 5 philosophers with 5 chopsticks (semaphores).
 A philosopher is either eating (with two chopsticks) or thinking.
 The philosophers share a circular table as shown below

 The table has a bowl of rice in the center and 5 single chopsticks.
 From time to time, a philosopher gets hungry and tries to pick up the 2
chopsticks that are closest to them.
 A philosopher may pick up only one chopstick at a time.
 Obviously, one cannot pick up a chopstick that is already in the hand of a neighbor
philosopher.

Dept. of CSE, CEC, Mangaluru Page 15


OPERATING SYSTEMS MODULE 3

 When hungry philosopher has both her chopsticks at the same time, she eats
without releasing her chopsticks.
 When she is finished eating, she puts down both of her chopsticks and starts thinking
again.
Problem objective: To allocate several resources among several processes in a deadlock-free &
starvation-free manner.
Solution using semaphore:
 Represent each chopstick with a semaphore; chopstick[5]
 A philosopher tries to grab a chopstick by executing a wait( ) on the semaphore.
 The philosopher releases her chopsticks by executing the signal( ) on the semaphores.
 This solution guarantees that no two neighbors are eating simultaneously.
Shared-data:
semaphore chopstick[5];

Initialization
chopstick[5]={1,1,1,1,1}

The structure of Dining- Philosopher i with semaphore solution:


do
{
wait (chopstick[i] );
wait (chopStick[ (i + 1) % 5] );
// eat
signal (chopstick[i] );
signal (chopstick[ (i + 1) % 5] );
// think
}
while (TRUE);
Disadvantage of Dining Philosopher problem with semaphore:
Deadlock may occur if all 5 philosophers become hungry simultaneously and grab their
left chopstick. When each philosopher tries to grab her right chopstick, she will be
delayed forever.
Three possible remedies to the deadlock problem:
1) Allow at most 4 philosophers to be sitting simultaneously at the table.

Dept. of CSE, CEC, Mangaluru Page 16


OPERATING SYSTEMS MODULE 3

2) Allow a philosopher to pick up her chopsticks only if both chopsticks are available.
3) Use an asymmetric solution; i.e. an odd philosopher picks up first her left
chopstick and then her right chopstick, whereas an even philosopher picks up her
right chopstick and then her left chopstick.

2.15 MONITORS
Need for Monitors
When programmers use semaphores incorrectly, following types of errors may occur:
1. Suppose that a process interchanges the order in which the wait() and signal() operations on the
semaphore mutex are executed, resulting in the following execution:

In this situation, several processes may be executing in their critical-sections


simultaneously, violating the mutual-exclusion requirement.
2. Suppose that a process replaces signal(mutex) with wait(mutex). That is, it executes

In this case, a deadlock will occur.


3. Suppose that a process omits the wait(mutex), or the signal(mutex), or both.
In this case, either mutual-exclusion is violated or a deadlock will occur.
Monitor is a high-level synchronization construct. It provides a convenient and effective
mechanism for process synchronization.
What are Monitors? Explain its uasage and implementation
A monitor is a module that encapsulates shared data structures, procedures that operate on shared
data, synchronization between concurrent procedure invocation and conditional variable.
Monitors Usage
Explain the syntax and schematic view of monitors
A monitor type presents a set of programmer-defined operations that are provided to
ensure mutual-exclusion within the monitor.
It also contains declaration of variables, bodies of procedures (or functions). A procedure defined
within a monitor can access only those variables declared locally within the monitor and its

Dept. of CSE, CEC, Mangaluru Page 17


OPERATING SYSTEMS MODULE 3

formal-parameters. Similarly, the local-variables of a monitor can be accessed by only the local-
procedures.

Syntax view of monitor

Only one process at a time is active within the monitor. To allow a process to wait within the
monitor, a condition variable must be declared, as

Schematic view of Monitor Monitor with condition variable


Condition variable can only be used with the following 2 operations:
x.signal(): This operation resumes exactly one suspended process. If no process is
suspended, then the signal operation has no effect.
x. wait(): The process invoking this operation is suspended until another process invokes
x.signal().
Dept. of CSE, CEC, Mangaluru Page 18
OPERATING SYSTEMS MODULE 3

Example:
Suppose when the x.signal() operation is invoked by a process P, there exists a suspended
process Q associated with condition x. Both processes can conceptually continue with
their execution. Two possibilities exist:
1) Signal and wait
P either waits until Q leaves the monitor or waits for other condition.
2) Signal and continue
Q either waits until P leaves the monitor or waits for other condition

DINING-PHILOSOPHERS SOLUTION USING MONITORS

Describe the monitor solution to the classical dining philosopher problem.


The restriction is a philosopher may pick up her chopsticks only if both of them are available.

A monitor solution to the dining-philosopher problem

Dept. of CSE, CEC, Mangaluru Page 19


OPERATING SYSTEMS MODULE 3

Description of the solution:


1. Philosopher may pick up her chopsticks only when both of them are available
2. Three states thinking, hungry and eating
3. Philosopher i can set the variable state[i]=EATING only when (state[i+4]%5 !=EATING)
&& (state[i+1]%5 !=EATING)
4. Condition self[5] in which philosopher can delay herself when she is hungry but is unable
to obtain chopsticks she needs
5. The distribution of the chopsticks is controlled by the monitor dp as shown above
6. Each philosopher, before starting to eat, must invoke the operation pickup().
This act may result in the suspension of the philosopher process.
7. After the successful completion of the operation, the philosopher may eat.
8. Following this, the philosopher invokes the putdown() operation.
9. Thus, philosopher i must invoke the operations pickup() and putdown() in the
sequence as given in code.
IMPLEMENTING A MONITOR USING SEMAPHORES
A process must execute wait(mutex) before entering the monitor and must execute signal(mutex)
after leaving the monitor.
Variables used:
Semaphore mutex; // (initially = 1)
Semaphore next; // (initially = 0)
int next-count =0;
where
 mutex is provided for each monitor.
 next is used a signaling process to wait until the resumed process either leaves or waits
 next-count is used to count the number of processes suspended
Each external procedure F is replaced by

Mutual-exclusion within a monitor is ensured.


How condition variables are implemented?

Dept. of CSE, CEC, Mangaluru Page 20


OPERATING SYSTEMS MODULE 3

Definition of x.wait() Definition of x.signal()

Resuming Processes within a Monitor


• If several processes queued on condition x, and x.signal() executed, which should be
resumed?
• FCFS frequently not adequate
• conditional-wait construct of the form x.wait(c)
– Where c is priority number
– Process with lowest number (highest priority) is scheduled next

Dept. of CSE, CEC, Mangaluru Page 21


OPERATING SYSTEMS MODULE 3

DEADLOCKS
3.1 DEADLOCKS
Define deadlock.

Deadlock is a situation where a set of processes are blocked because each process is holding a resource
and waiting for another resource held by some other process.

Real life example:


When 2 trains are coming toward each other on same track and there is only one track,
none of the trains can move once they are in front of each other.

Similar situation occurs in operating systems when there are two or more processes hold some
resources and wait for resources held by other(s).
3.2 SYSTEM MODEL

A system consists of finite number of resources. (For ex: memory, printers, CPUs). These resources are
distributed among number of processes. A process must request a resource before using it and release
the resource after using it. The process can request any number of resources to carry out a given task.
The total number of resource requested must not exceed the total number of resources available.

In normal operation, a process must perform following tasks in sequence:


1. Request

If the request cannot be granted immediately (for ex: the resource is being used by another
process), then the requesting-process must wait for acquiring the resource.

For example: open( ), malloc( ), new( ), and request( )


2. Use

The process uses the resource. For example: prints to the printer or reads from the file.
3. Release

The process releases the resource. So that, the resource becomes available for other processes.

For example: close( ), free( ), delete( ), and release( ).

A set of processes is deadlocked when every process in the set is waiting for a resource that is
currently allocated to another process in the set. Deadlock may involve different types of
resources.

As shown in below figure , Both processes P1 & P2 need resources to continue execution.
Dept. of CSE, CEC, Mangaluru Page 22
OPERATING SYSTEMS MODULE 3

P1 requires additional resource R1and is in possession of resource R2. P2 requires


additional resource R2 and is in possession of R1. Thus, neither process can continue.

Multithread programs are good candidates for deadlock because they compete for shared resources.

3.3 DEADLOCK CHARACTERIZATION


In a deadlock, processes never finish executing, and system resources are tied up, preventing
other jobs from starting.
NECESSARY CONDITIONS

**********What are the necessary conditions for deadlock? OR


***********What are the characteristics of deadlock?

There are four conditions that are necessary to achieve deadlock:


1. Mutual Exclusion
 Only one process at a time can use a resource.
 At least one resource must be held in a non-sharable mode.
 If any other process requests this resource, then the requesting-process must

wait for the resource to be released.


2. Hold and Wait

A process must be simultaneously holding at least one resource and waiting to acquire additional
resources held by the other process.
3. No Preemption

Once a process is holding a resource ( i.e. once its request has been granted ), then that resource
cannot be taken away from that process until the process voluntarily releases it.
4. Circular Wait
A set of processes {P0, P1, P2, . . ., PN } must exist 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.

Dept. of CSE, CEC, Mangaluru Page 23


OPERATING SYSTEMS MODULE 3

RESOURCE-ALLOCATION-GRAPH (RAG)

The resource-allocation-graph (RAG) is a directed graph that can be used to describe the deadlock
situation.

RAG consists of a
i. Set of vertices (V) and
ii. Set of edges (E).

V is divided into two types of nodes


1) Process vertex or node; P={P1,P2……..Pn} i.e., set consisting of all active processes in
the system.
2) Resource vertex or node; R={R1,R2……….Rn} i.e., set consisting of all resource types
in the system.

E is divided into two types of edges:


1) Request Edge
 A directed-edge Pi → Rj is called a request edge.
 Pi → Rj indicates that process Pi has requested a resource Rj.
2) Assignment Edge
 A directed-edge Rj → Pi is called an assignment edge.
 Rj → Pi indicates that a resource Rj has been allocated to process Pi.

NOTE:

Suppose that process Pi requests resource Rj.; Here, the request for Rj from Pi can be granted only if the
converting request-edge to assignment-edge do not form a cycle in the resource-allocation graph.

Pictorially, we represent each process Pi as a circle. We represent each resource-type Rj as a rectangle.

Dept. of CSE, CEC, Mangaluru Page 24


OPERATING SYSTEMS MODULE 3

As shown in below figures, the RAG illustrates the following 3 situation

Describe RAG i) With deadlock ii) With a cycle but no deadlock


1) RAG with a deadlock
2) RAG with a cycle and deadlock
3) RAG with a cycle but no deadlock

1.) RAG with a deadlock 2). With a cycle and deadlock 3). With cycle but no deadlock
CONCLUSION:
1) If a graph contains no cycles, then the system is not deadlocked.
2) If the graph contains a cycle and if only one instance per resource type is used, then
deadlock will occur.
3) If the graph contains a cycle and if several instances per resource type is used, then there
is a possibility of deadlock but not necessarily present
METHODS FOR HANDLING DEADLOCKS

***Briefly explain the methods for handling deadlock

Dept. of CSE, CEC, Mangaluru Page 25


OPERATING SYSTEMS MODULE 3

There are three ways of handling deadlocks:


1. Deadlock prevention or Avoidance: Do not allow the system to get into a deadlocked state. In
order to prevent deadlocks, use set of methods for ensuring that at least one of the necessary
conditions for deadlock cannot hold. In order to avoid deadlocks, the system must have additional
information about all processes, such that which resources a process will request and use during
its lifetime. With this additional knowledge, it can decide for each request whether or not the
process should wait.

2. Deadlock detection and recovery: Abort a process or preempt some resources when deadlocks
are detected. Deadlock detection is fairly straightforward, but deadlock recovery requires
either aborting processes or preempting resources.

3. Ignore the problem all together and pretend that deadlocks never occur in the system: This
solution is used by most operating system
3.4 DEADLOCK-PREVENTION

How can deadlock be prevented? Describe any three of them.

Deadlocks can be eliminated by preventing (making False) at least one of the four required conditions:
1) Mutual exclusion
2) Hold-and-wait
3) No preemption
4) Circular-wait.
Mutual Exclusion

 This condition must hold for non-sharable resources. For example: A printer cannot be
simultaneously shared by several processes.
 On the other hand, shared resources do not lead to deadlocks. For example: Simultaneous
access can be granted for read-only file.
 A process never waits for accessing a sharable resource.
 In general, we cannot prevent deadlocks by denying the mutual-exclusion condition
because some resources are non-sharable by default.
Hold and Wait:

To prevent this condition it must be ensure that, whenever a process requests a resource, it does not hold
any other resources.

There are several solutions to this problem.


 Each process must be allocated with all of its resources before it begins execution
Dept. of CSE, CEC, Mangaluru Page 26
OPERATING SYSTEMS MODULE 3

 A process must request a resource only when the process has none allocated to it. A process
may request some resources and use them. Before it can request any additional resources,
however, it must release all the resources that it is currently allocated
No Preemption

To prevent this condition the resources must be preempted.

There are several solutions to this problem.


 If a process is holding some resources and requests another resource that cannot be
immediately allocated to it, then all resources currently being held are preempted.
 The preempted resources are added to the list of resources for which the process is waiting.
 The process will be restarted only when it regains the old resources and the new resources
that it is requesting.
 When a process request resources, we check whether they are available or not. If they
are available allocate them, if they are not check whether they are available with process
waiting for additional resource if so preempt desired resources from the waiting process.
Circular-Wait
 To ensure that this condition never holds is to impose a total ordering of all resource types by
assigning numbers to all resources, and require that each process requests resources in an
increasing/decreasing order of enumeration.
 Require that whenever a process requests a resource, it has released resources with a
lower number.
 One big challenge in this scheme is determining the relative ordering of the different
resources.
3.5 DEADLOCK AVOIDANCE

The general idea behind deadlock avoidance is to prevent deadlocks from ever happening. Deadlocks are
requiring additional information about how resources are to be requested.

Deadlock-avoidance algorithm
 Requires more information about each process, and
 Tends to lead to low device utilization.

For example:
1) In simple algorithms, the scheduler only needs to know the maximum number of
each resource that a process might potentially use.
2) In complex algorithms, the scheduler can also take advantage of the schedule of

Dept. of CSE, CEC, Mangaluru Page 27


OPERATING SYSTEMS MODULE 3

exactly what resources may be needed in what order.

A deadlock-avoidance algorithm dynamically examines the resources allocation state to ensure


that a circular-wait condition never exists. The resource-allocation state is defined by the
number of available and allocated resources and the maximum demand of each process.

SAFE STATE

A state is safe if the system can allocate all resources requested by all processes without entering a
deadlock state.
A state is safe if there exists a safe sequence of processes {P0, P1, P2, ..., PN} such that the requests
of each process(Pi) can be satisfied by the currently available resources.

If a safe sequence does not exist, then the system is in an unsafe state, which may lead to deadlock. All
safe states are deadlock free, but not all unsafe states lead to deadlocks.

Safe, Unsafe and Deadlock state spaces


DEADLOCK AVOIDANCE USING RESOURCE ALLOCATION GRAPH ALGORITHM
If resource categories have only single instances of their resources, then deadlock states can be
detected by cycles in the resource-allocation graphs.
In this case, unsafe states can be recognized and avoided by augmenting the resource-allocation
graph with claim edges (denoted by a dashed line).
Claim edge Pi → Rj indicated that process Pi may request resource Rj at some time in future.
The important steps are as below:

Dept. of CSE, CEC, Mangaluru Page 28


OPERATING SYSTEMS MODULE 3

1. When a process Pi requests a resource Rj, the claim edge Pi → Rj is converted to a request
edge.
2. Similarly, when a resource Rj is released by the process Pi, the assignment edge Rj → Pi is
reconverted as claim edge Pi → Rj.
3. The request for Rj from Pi can be granted only if the converting request edge to assignment
edge do not form a cycle in the resource allocation graph.
To apply this algorithm, each process Pi must know all its claims before it starts executing.
Conclusion:
 If no cycle exists, then the allocation of the resource will leave the system in a safe state.
 If cycle is found, system is put into unsafe state and may cause a deadlock.
For example: Consider a resource allocation graph shown in Figure below

Suppose P2 requests R2. Though R2 is currently free, we cannot allocate it to P2 as this action will
create a cycle in the graph as shown in below Figure. This cycle will indicate that the system is in
unsafe state: because, if P1 requests R2 and P2 requests R1 later, a deadlock will occur.

Unsafe State In Resource-Allocation Graph

Problem:
The resource-allocation graph algorithm is not applicable when there are multiple instances for
Dept. of CSE, CEC, Mangaluru Page 29
OPERATING SYSTEMS MODULE 3

each resource.
Solution: Use banker's algorithm.

BANKERS ALGORITHM

This algorithm is applicable to the system with multiple instances of each resource types. However, this
algorithm is less efficient then the resource-allocation-graph algorithm. When a process starts up, it
must declare the maximum number of resources that it may need. This number may not exceed the
total number of resources in the system. When a request is made, the system determines whether
granting the request would leave the system in a safe state.

If the system in a safe state, then the resources are allocated;

else the process must wait until some other process releases enough resources.

Assumptions: Let n = number of processes in the system Let m = number of resources types.

Following data structures are used to implement the banker’s algorithm.

Explain the data structures used in Bankers algorithm.


Available [m]
 This vector indicates the no. of available resources of each type.
 If Available[j]=k, then k instances of resource type Rj is available.
Max [n][m]
 This matrix indicates the maximum demand of each process of each resource.
 If Max[i,j]=k, then process Pi may request at most k instances of resource type Rj.
Allocation [n][m]
 This matrix indicates no. of resources currently allocated to each process.
 If Allocation[i,j]=k, then Pi is currently allocated k instances of Rj.

Need [n][m]
 This matrix indicates the remaining resources need of each process.
 If Need[i,j]=k, then Pi may need k more instances of resource Rj to complete its task.
 So, Need[i,j] = Max[i,j] - Allocation[i]

Write and explain Bankers algorithm. (explain both safety and Resource request algorithm)
This algorithm is applicable to the system with multiple instances of each resource types.

When a process starts up, it must declare the maximum number of resources that it may need. This
number may not exceed the total number of resources in the system. When a request is made, the
Dept. of CSE, CEC, Mangaluru Page 30
OPERATING SYSTEMS MODULE 3

system determines whether granting the request would leave the system in a safe state.

If the system in a safe state, then the resources are allocated;

else the process must wait until some other process releases enough resources.

Assumptions: Let n = number of processes in the system Let m = number of resources types.
Following data structures are used to implement the banker’s algorithm
Available [m], Max [n][m], Allocation [n][m], Need [n][m]

The Banker’s algorithm has two parts: 1) Safety Algorithm


2) Resource – Request Algorithm
Safety Algorithm
Step 1:
Let Work and Finish be two vectors of length m and n respectively.
Initialize:
Work = Available
Finish[i] = false for i=1,2,3,…….n
Step 2:
Find an index(i) such that both
a) Finish[i] = false

b) Need i <= Work.


If no such i exist, then go to step 4
Step 3:
Set:
Work = Work + Allocation(i)
Finish[i] = true
Go to step 2
Step 4:
If Finish[i] = true for all i, then the system is in safe state.

Resource-Request Algorithm

****Explain Resource Request Algorithm

This algorithm determines if a new request is safe, and grants it only if it is safe to do so. When a request
is made ( that does not exceed currently available resources ), pretend it has been granted, and then
see if the resulting state is a safe one. If so, grant the request, and if not, deny the request.

Let Requesti be the request vector of process Pi.

Dept. of CSE, CEC, Mangaluru Page 31


OPERATING SYSTEMS MODULE 3

If Requesti [j]=k, then process Pi wants k instances of the resource type Rj.
Step 1:
If Requesti <= Needi then go to step 2
else
Raise an error condition, since the process has exceeded its maximum claim.
Step 2:
If Requesti <= Available then go to step 3
else
Pi must wait, since the resources are not available.
Step 3:
If the system wants to allocate the requested resources to process Pi then modify the
state as follows:
Available = Available – Requesti
Allocationi = Allocationi + Requesti
Needi = Needi – Requesti
Step 4:
If the resulting resource-allocation state is safe, then
i) transaction is complete and
ii) Pi is allocated its resources.
Step 5:
If the new state is unsafe,then
i) Pi must wait for Requesti and
ii) Old resource-allocation state is restored.

An Illustrative Example

1. Consider the following snapshot of a system:

Allocation Max Available


A B C A B C A B C
P0 0 1 0 7 5 3 3 3 2
P1 2 0 0 3 2 2

Dept. of CSE, CEC, Mangaluru Page 32


OPERATING SYSTEMS MODULE 3

P2 3 0 3 9 0 2
P3 2 1 1 2 2 2
P4 0 0 2 4 3 3

Answer the following questions using Banker's algorithm.


i) What is the content of the matrix need?
ii) Is the system in a safe state?
iii) If a request from process P1 arrives for (1, 0, 2) can the request be granted immediately?
Solution:
The content of the matrix Need is given by Need = Max - Allocation
So, the content of Need Matrix is:
Need
A B C
P0 7 4 3
P1 1 2 2
P2 6 0 0
P3 0 1 1
P4 4 3 1
Applying the Safety algorithm on the given system:

Step 1: Initialization
Work = Available ie: Work = 3 3 2
Process P0 P1 P2 P3 P4
Finish False False False False False
Step 2: For i= 0
Finish [P0] = false and Need [P0] <= Work i.e. (7 4 3) <= (3 3 2) ie: false So P0 must wait.
Step 2: For i=1
Finish [P1] = false and Need [P1] <= Work i.e. (1 2 2) <= (3 3 2) ie: True, So P1 must be kept
in safe sequence.
Step 3: Work = Work + Allocation [P1] = (3 3 2) + (2 0 0) = (5 3 2)

Process P0 P1 P2 P3 P4
Finish False True False False False
Step 2: For i=2
Finish[P2] = false and Need[P2] <= Work i.e. (6 0 0) <= (5 3 2) ie: false, So P2 must wait.
Step 2: For i=3

Dept. of CSE, CEC, Mangaluru Page 33


OPERATING SYSTEMS MODULE 3

Finish[P3] = false and Need[P3] <= Work i.e. (0 1 1) <= (5 3 2) ie: True, So P3 must be kept in
safe sequence.
Step 3: Work = Work + Allocation [P3] = (5 3 2) + (2 1 1) = (7 4 3)

Process P0 P1 P2 P3 P4
Finish False True False True False
Step 2: For i=4
Finish[P4] = false and Need[P4] <= Work i.e. (4 3 1) <= (7 4 3) ie: True, So P4 must be kept in
safe sequence.
Step 3: Work = Work + Allocation [P4] = (7 4 3) + (0 0 2) = (7 4 5)

Process P0 P1 P2 P3 P4
Finish False True False True True
Step 2: For i=0
Finish[P0] = false and Need[P0] <= Work i.e. (7 4 3) <= (7 4 5) ie: True, So P0 must be kept in
safe sequence.
Step 3: Work = Work + Allocation [P0] = (7 4 5) + (0 1 0) = (7 5 5)

Process P0 P1 P2 P3 P4
Finish True True False True True
Step 2: For i=2
Finish[P2] = false and Need[P2] <= Work i.e. (6 0 0) <= (7 5 5) ie: True, So P2 must be kept in
safe sequence.
Step 3: Work = Work + Allocation [P2] = (7 5 5) + (3 0 2) = (10, 5 7)

Process P0 P1 P2 P3 P4
Finish True True True True True
Step 4: Finish[Pi] = True for 0 <= i<= 4
Hence, the system is currently in a safe state. The safe sequence is <P1, P3, P4, P0, P2>.
ii) Conclusion: Yes, the system is currently in a safe state.

Solution (iii): P1 requests (1 0 2) i.e. Request [P1] = (1 0 2)


To decide whether the request is granted, we use Resource Request algorithm.
Step 1: Request[P1] <= Need[P1] i.e. (1 0 2) <= (1 2 2) ie: true.
Step 2: Request[P1] <=Available (at time t0, when system snapshot is taken)
i.e. (1 0 2) <= (3 3 2) ie: true.
Step 3: Available = Available – Request [P1] = (3 3 2) - (1 0 2) = (2 3 0)
Allocation[P1] = Allocation[P1] + Request[P1] = (2 0 0) + (1 0 2)= (3 0 2)
Dept. of CSE, CEC, Mangaluru Page 34
OPERATING SYSTEMS MODULE 3

Need[P1] = Need[P1] – Request[P1] = (1 2 2) - (1 0 2)= (0 2 0)

We arrive at the following new system state:


Allocation Max Available
A B C A B C A B C
P0 0 1 0 7 5 3 2 3 0
P1 3 0 2 3 2 2
P2 3 0 2 9 0 2
P3 2 1 1 2 2 2
P4 0 0 2 4 3 3

The content of the matrix Need is given by Need = Max - Allocation


So, the content of Need Matrix is:

Need
A B C
P0 7 4 3
P1 0 2 0
P2 6 0 0
P3 0 1 1
P4 4 3 1
To determine whether this new system state is safe, we again execute Safety algorithm.
Step 1: Initialization
Work = Available ie: Work = 2 3 0
Process P0 P1 P2 P3 P4
Finish False False False False False
Step 2: For i= 0
Finish [P0] = false and Need [P0] <= Work i.e. (7 4 3) <= (2 3 0) ie: false So P0 must wait.
Step 2: For i=1
Finish [P1] = false and Need [P1] <= Work i.e. (0 2 0) <= (2 3 0) ie: True, So P1 must be kept
in safe sequence.
Step 3: Work = Work + Allocation [P1] = (2 3 0) + (3 0 2) = (5 3 2)

Process P0 P1 P2 P3 P4
Finish False True False False False
Step 2: For i= 2
Dept. of CSE, CEC, Mangaluru Page 35
OPERATING SYSTEMS MODULE 3

Finish [P2] = false and Need [P2] <= Work i.e. (6 0 0) <= (5 3 2) ie: false So P2 must wait.
Step 2: For i=3
Finish [P3] = false and Need [P3] <= Work i.e. (0 1 1) <= (5 3 2) ie: True, So P3 must be kept
in safe sequence.
Step 3: Work = Work + Allocation [P3] = (5 3 2) + (2 1 1) = (7 4 3)

Process P0 P1 P2 P3 P4
Finish False True False True False

Step 2: For i=4


Finish [P4] = false and Need [P4] <= Work i.e. (4 3 1) <= (7 4 3) ie: True, So P4 must be kept
in safe sequence.
Step 3: Work = Work + Allocation [P4] = (7 4 3) + (0 0 2) = (7 4 5)

Process P0 P1 P2 P3 P4
Finish False True False True True
Step 2: For i =0
Finish [P0] = false and Need [P0] <= Work i.e. (7 4 3) <= (7 4 5) ie: True, So P0 must be kept
in safe sequence.
Step 3: Work = Work + Allocation [P0] = (7 4 5) + (0 1 0) = (7 5 5)

Process P0 P1 P2 P3 P4
Finish True True False True True
Step 2: For i =2
Finish [P2] = false and Need [P2] <= Work i.e. (6 0 0) <= (7 5 5) ie: True, So P2 must be kept
in safe sequence.
Step 3: Work = Work + Allocation [P2] = (7 5 5) + (3 0 2) = (10, 5, 7)

Process P0 P1 P2 P3 P4
Finish True True True True True
Step 4: Finish[Pi] = True for 0 <= i<= 4
Hence, the system is currently in a safe state. The safe sequence is <P1, P3, P4, P0, P2>.
Conclusion: Since the system is in safe sate, the request can be granted.

Dept. of CSE, CEC, Mangaluru Page 36


OPERATING SYSTEMS MODULE 3

2.Consider the following snapshot of a system:


Allocation Max Available
A B C A B C A B C
P0 0 0 2 0 0 4 1 0 2
P1 1 0 0 2 0 1
P2 1 3 5 1 3 7
P3 6 3 2 8 4 2
P4 1 4 3 1 5 7
Answer the following questions using Banker's algorithm.
i) What is the content of the matrix need?
ii) Is the system in a safe state?
iii) If a request from process P2 arrives for (0, 0, 2) can the request be granted immediately?
Solution:
i) The content of the matrix Need is given by Need = Max - Allocation
So, the content of Need Matrix is:
Need
A B C
P0 0 0 2
P1 1 0 1
P2 0 0 2
P3 2 1 0
P4 0 1 4

ii) Applying the Safety algorithm on the given system:

Step 1: Initialization
Work = Available ie: Work = (1 0 2)
Process P0 P1 P2 P3 P4
Finish False False False False False
Step 2: For i=0
Need[P0] <= work ie: (0 0 2) <= (1 0 2) ie: True, So P0 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P0] = (1 0 2) + (0 0 2) = (1 0 4)
Set Finish[P0] = True
Step 2: For i=1
Need[P1] <= work ie: (1 0 1) <= (1 0 4) ie: True, So P1 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P1] = (1 0 4) + (1 0 0) = (2 0 4)
Set Finish[P1] = True

Dept. of CSE, CEC, Mangaluru Page 37


OPERATING SYSTEMS MODULE 3

Step 2: For i=2


Need[P2] <= work ie: (0 0 2) <= (2 0 4) ie: True, So P2 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P2] = (2 0 4) + (1 3 5) = (3 3 9)
Set Finish[P2] = True
Step 2: For i=3
Need[P3] <= work ie: (2 1 0) <= (3 3 9) ie: True, So P3 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P3] = (3 3 9) + (6 3 2) = (9, 6, 11)
Set Finish[P3] = True
Step 2: For i=4
Need[P4] <= work ie: (0 1 4) <= (9, 6, 11) ie: True, So P4 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P4] = (9, 6, 11) + (1 4 3) = (10, 10, 14)
Set Finish[P4] = True
Step 4: Finish[Pi] = True for 0 <= i<= 4
Hence, the system is currently in a safe state. The safe sequence is <P0, P1, P2, P3, P4>.

Solution (iii): P2 requests (0 0 2) i.e. Request [P2] = (0 0 2)


To decide whether the request is granted, we use Resource Request algorithm.
Step 1: Request[P2] <= Need[P2] i.e. (0 0 2) <= (0 0 2) ie: true.
Step 2: Request[P2] <=Available (at time t0, when system snapshot is taken)
i.e. (0 0 2) <= (1 0 2) ie: true.
Step 3: Available = Available – Request [P2] = (1 0 2) - (0 0 2) = (1 0 0)
Allocation[P2] = Allocation[P2] + Request[P2] = (1 3 5) + (0 0 2)= (1 3 7)
Need[P2] = Need[P2] – Request[P2] = (0 0 2) - (0 0 2) = (0 0 0)

We arrive at the following new system state:


Allocation Max Available
A B C A B C A B C
P0 0 0 2 0 0 4 1 0 0
P1 1 0 0 2 0 1
P2 1 3 7 1 3 7
P3 6 3 2 8 4 2
P4 1 4 3 1 5 7

The content of the matrix Need is given by Need = Max - Allocation


So, the content of Need Matrix is:
Need
Dept. of CSE, CEC, Mangaluru Page 38
OPERATING SYSTEMS MODULE 3

A B C
P0 0 0 2
P1 1 0 1
P2 0 0 0
P3 2 1 0
P4 0 1 4
To determine whether this new system state is safe, we again execute Safety algorithm.
Step 1: Initialization
Work = Available ie: Work = (1 0 0)
Process P0 P1 P2 P3 P4
Finish False False False False False
Step 2: For i=0
Need[P0] <= work ie: (0 0 2) <= (1 0 0) ie: False, So P0 must wait.
Step 2: For i=1
Need[P1] <= work ie: (1 0 1) <= (1 0 0) ie: False So P1 must wait.
Step 2: For i=2
Need[P2] <= work ie: (0 0 0) <= (1 0 0) ie: True, So P2 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P2] = (1 0 0) + (1 3 7) = (2 3 7)
Set Finish[P2] = True
Step 2: For i=3
Need[P3] <= work ie: (2 1 0) <= (2 3 7) ie: True, So P3 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P3] = (2 3 7) + (6 3 2) = (8, 6, 9)
Set Finish[P3] = True
Step 2: For i=4
Need[P4] <= work ie: (0 1 4) <= (8, 6, 9) ie: True, So P4 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P4] = (8, 6, 9) + (1 4 3) = (9, 10, 12)
Set Finish[P4] = True
Step 2: For i=0
Need[P0] <= work ie: (0 0 2) <= (9, 10, 12) ie: True, So P0 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P0] = (9, 10, 12) + (0 0 2) = (9, 10, 14)
Set Finish[P0] = True
Step 2: For i=1
Need[P1] <= work ie: (1 0 1) <= (9, 10, 14) ie: True, So P1 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P1] = (9, 10, 14) + (1 0 0) = (10, 10, 14)
Set Finish[P1] = True
Step 4: Finish[Pi] = True for 0 <= i<= 4
Hence, the system is currently in a safe state. The safe sequence is <P2, P3, P4, P0, P2>.
Conclusion: Since the system is in safe sate, the request can be granted.

3.Consider the following snapshot of a system:

Dept. of CSE, CEC, Mangaluru Page 39


OPERATING SYSTEMS MODULE 3

Allocation Max Available


A B C D A B C D A B C D
P0 0 0 1 2 0 0 1 2 1 5 2 0
P1 1 0 0 0 1 7 5 0
P2 1 3 5 4 2 3 5 6
P3 0 6 3 2 0 6 5 2
P4 0 0 1 4 0 6 5 6
Answer the following questions using Banker's algorithm.
i) What is the content of the matrix need?
ii) Is the system in a safe state?
iii) If a request from process P1 arrives for (0, 4, 2, 0) can the request be granted?
The content of the matrix Need is given by Need = Max - Allocation
So, the content of Need Matrix is:
Need
A B C D
P0 0 0 0 0
P1 0 7 5 0
P2 1 0 0 2
P3 0 0 2 0
P4 0 6 4 2

Step 1: Initialization
Work = Available ie: Work = (1 5 2 0)
Process P0 P1 P2 P3 P4
Finish False False False False False
Step 2: For i=0
Need[P0] <= work ie: (0 0 0 0) <= (1 5 2 0) ie: True, So P0 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P0] = (1 5 2 0) + (0 0 1 2) = (1 5 3 2)
Set Finish[P0] = True
Step 2: For i=1
Need[P1] <= work ie: (0 7 5 0) <= (1 5 3 2) ie: False, So P1 must wait
Step 2: For i=2
Need[P2] <= work ie: (1 0 0 2) <= (1 5 3 2) ie: True, So P2 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P2] = (1 5 3 2) + (1 3 5 4) = (2 8 8 6)
Set Finish[P2] = True
Step 2: For i=3
Dept. of CSE, CEC, Mangaluru Page 40
OPERATING SYSTEMS MODULE 3

Need[P3] <= work ie: (0 0 2 0) <= (2, 8, 8, 6) ie: True, So P3 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P3] = (2, 8, 8, 6) + (0 6 3 2) = (2, 14, 11, 8)
Set Finish[P3] = True
Step 2: For i=4
Need[P4] <= work ie: (0 6 4 2) <= (2, 14, 11, 8) ie: True, So P4 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P4] = (2, 14, 11, 8) + (0 0 1 4) = (2, 14, 12, 12)
Set Finish[P4] = True
Step 2: For i=1
Need[P1] <= work ie: (0 7 5 0) <= (2, 14, 12, 12)ie: True, So P1 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P1] = (2, 14, 12, 12) + (1 0 0 0) = (3, 14, 12, 12)
Set Finish[P1] = True
Step 4: Finish[Pi] = True for 0 <= i<= 4
Hence, the system is currently in a safe state. The safe sequence is <P0, P2, P3, P4, P0>.
Solution (iii): P1 requests (0, 4, 2, 0) i.e. Request [P1] = (0, 4, 2, 0)
To decide whether the request is granted, we use Resource Request algorithm.
Step 1: Request[P1] <= Need[P1] i.e. (0, 4, 2, 0) <= (0, 7, 5, 0) ie: true.
Step 2: Request[P1] <=Available (at time t0, when system snapshot is taken)
i.e. (0, 4, 2, 0) <= (1, 5, 2, 0) ie: true.
Step 3: Available = Available – Request [P1] = (1, 5, 2, 0) - (0, 4, 2, 0) = (1, 1, 0, 0)
Allocation[P1] = Allocation[P1] + Request[P1] = (1 0 0 0) + (0, 4, 2, 0) = (1, 4, 2, 0)
Need[P1] = Need[P1] – Request[P1] = (0, 7, 5, 0) - (0, 4, 2, 0) = (0, 3, 3, 0)
We arrive at the following new system state:
Allocation Max Available
A B C D A B C D A B C D
P0 0 0 1 2 0 0 1 2 1 1 0 0
P1 1 4 2 0 1 7 5 0
P2 1 3 5 4 2 3 5 6
P3 0 6 3 2 0 6 5 2
P4 0 0 1 4 0 6 5 6

The content of the matrix Need is given by Need = Max - Allocation


So, the content of Need Matrix is:
Need
A B C D
P0 0 0 0 0

Dept. of CSE, CEC, Mangaluru Page 41


OPERATING SYSTEMS MODULE 3

P1 0 3 3 0
P2 1 0 0 2
P3 0 0 2 0
P4 0 6 4 2
To determine whether this new system state is safe, we again execute Safety algorithm.
Step 1: Initialization
Work = Available ie: Work = (1, 1, 0, 0)
Process P0 P1 P2 P3 P4
Finish False False False False False
Step 2: For i=0
Need[P0] <= work ie: (0 0 0 0) <= (1 1 0 0) ie: True, So P0 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P0] = (1 1 0 0) + (0 0 1 2) = (1 1 1 2)
Set Finish[P0] = True
Step 2: For i=1
Need[P1] <= work ie: (0 3 3 0) <= (1 1 1 2) ie: False, So P1 must wait
Step 2: For i=2
Need[P2] <= work ie: (1 0 0 2) <= (1 1 1 2) ie: True, So P2 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P2] = (1 1 1 2) + (1 3 5 4) = (2 4 6 6)
Set Finish[P2] = True
Step 2: For i = 3
Need[P3] <= work ie: (0 0 2 0) <= (2 4 6 6) ie: True, So P3 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P3] = (2 4 6 6) + (0 6 3 2) = (2, 10, 9, 8)
Set Finish[P3] = True
Step 2: For i=4
Need[P4] <= work ie: (0 6 4 2) <= (2, 10, 9, 8) ie: True, So P4 must be kept in safe sequence.
Step3: Therefore work = work + Allocation [P4] = (2, 10, 9, 8) + (0 0 1 4) = (2, 10, 10, 12)
Set Finish[P4] = True
Step 2: For i=1
Need[P1] <= work ie: (0 3 3 0) <= (2, 10, 10, 12) ie: True, So P1 must be kept in safe
sequence.
Step3: Therefore work = work + Allocation [P1] = (2, 10, 10, 12) + (1 4 2 0) = (3, 14, 12, 12)
Set Finish[P1] = True
Step 4: Finish[Pi] = True for 0 <= i<= 4
Hence, the system is currently in a safe state. The safe sequence is <P0, P2, P3, P4, P1>.
Conclusion: Since the system is in safe sate, the request can be granted.

Dept. of CSE, CEC, Mangaluru Page 42


OPERATING SYSTEMS MODULE 3

3.6 DEADLOCK DETECTION


If a system does not use either of deadlock-prevention or deadlock-avoidance algorithm then a
deadlock may occur. In this environment, the system must provide:
1. An algorithm to examine the system-state to determine whether a deadlock has occurred.
2. An algorithm to recover from the deadlock.
SINGLE INSTANCE OF EACH RESOURCE TYPE
If all the resources have only a single instance, then deadlock detection-algorithm can be defined
using a wait-for-graph. The wait-for-graph is applicable to only a single instance of a resource
type.
A wait-for-graph (WAG) is a variation of the resource-allocation-graph. The wait-for-graph can
be obtained from the resource-allocation-graph by removing the resource nodes and collapsing
the appropriate edges.
An edge from Pi to Pj implies that process Pi is waiting for process Pj to release a resource that Pi
needs. An edge Pi → Pj exists if and only if the corresponding graph contains two edges Pi → Rq
and Rq → Pj.
For example:
For the following resource Allocation Graph, write the wait-for –graph.
Consider resource-allocation-graph shown in below Figure

The corresponding wait-for-graph is shown in below Figure:

Dept. of CSE, CEC, Mangaluru Page 43


OPERATING SYSTEMS MODULE 3

A deadlock exists in the system if and only if the wait-for-graph contains a cycle. To detect
deadlocks, the system needs to 1) Maintain the wait-for-graph and 2) Periodically execute an
algorithm that searches for a cycle in the graph.
SEVERAL INSTANCES OF A RESOURCE TYPE
The wait-for-graph is applicable to only a single instance of a resource type. However, the wait-
for-graph is not applicable to a multiple instance of a resource type. The following detection-
algorithm can be used for a multiple instance of a resource type.
Assumptions:
Let ‘n’ be the number of processes in the system Let ‘m’ be the number of resources types.
Following data structures are used to implement this algorithm.
Available [m]
This vector indicates the no. of available resources of each type.
If Available[j]=k, then k instances of resource type Rj is available.
Allocation [n][m]
This matrix indicates no. of resources currently allocated to each process.
If Allocation[i,j]=k, then Pi is currently allocated k instances of Rj.
Request [n][m]
This 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.

DETECTION-ALGORITHM USAGE
Dept. of CSE, CEC, Mangaluru Page 44
OPERATING SYSTEMS MODULE 3

The detection-algorithm must be executed based on following factors:


1. The frequency of occurrence of a deadlock.
2. The no. of processes affected by the deadlock.
If deadlocks occur frequently, then the detection-algorithm should be executed frequently.
Resources allocated to deadlocked-processes will be idle until the deadlock is broken.
Problem:
Deadlock occurs only when some processes make a request that cannot be granted immediately.
Solution 1:
The deadlock-algorithm must be executed whenever a request for allocation cannot be granted
immediately. In this case, we can identify set of deadlocked-processes and specific process causing
the deadlock.
Solution 2:
The deadlock-algorithm must be executed in periodic intervals. For example: once in an hour, that
is whenever CPU utilization drops below certain threshold
3.7 RECOVERY FROM DEADLOCK
********Explain different methods to recover from deadlock
The 3 different deadlock recovery methods are:
1. Inform the system-operator for manual intervention of deadlocked process.
2. Process Termination
3. Resource Preemption
Process Termination
Two methods to remove deadlocks:
i. Terminate all deadlocked-processes. This method will definitely break the deadlock-cycle.
However, this method incurs great expense. This is because a) Deadlocked-processes
might have computed for a long time. b) Results of these partial computations must be
discarded. c) Probably, the results must be re-computed later.
ii. Terminate one process at a time until the deadlock-cycle is eliminated: This method incurs
large overhead. This is because after each process is aborted, deadlock-algorithm must be
executed to determine if any other process is still deadlocked.
For process termination, following factors need to be considered:
1. Priority of the process
2. How long process has computed, and how much longer to completion
3. Resources the process has used
4. Resources process needs to complete

Dept. of CSE, CEC, Mangaluru Page 45


OPERATING SYSTEMS MODULE 3

5. How many processes will need to be terminated


6. Is process interactive or batch?
Resource Preemption
Some resources are taken from one or more deadlocked-processes. These resources are given to
other processes until the deadlock-cycle is broken. Three issues need to be considered:
1. Selecting a victim: Which resources/processes are to be pre-empted (or blocked)? The order
of pre-emption must be determined to minimize cost. a) The cost factors includes the time
taken by deadlocked-process for computation. b) The number of resources used by the
deadlocked-processes.
2. Rollback: If a resource is taken from a process, the process cannot continue its normal
execution. In this case, the process must be rolled-back to break the deadlock. This method
requires the system to keep more information about the state of all running processes
3. Starvation: In a system where victim-selection is based on cost-factors, the same process may
be always picked as a victim. As a result, this process never completes its designated task. To
ensure a process is picked as a victim only a (small) finite number of times.

Dept. of CSE, CEC, Mangaluru Page 46

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy