0% found this document useful (0 votes)
338 views

Os Unit 3 Class Notes

Uploaded by

23102208
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)
338 views

Os Unit 3 Class Notes

Uploaded by

23102208
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/ 17

UNIT III - PROCESS SYNCHRONIZATION AND DEADLOCKS

Process Synchronization - The critical-section problem, Perterson’s Solution-Synchronization hardware,


Mutex locks, Semaphores, Monitors, Liveness- Classic problems of synchronization-Bounded Buffer
Problem - Readers Writers Problem-Dining Philosopher’s Problem-Barber’s Shop Problem - Deadlock -
System model, Deadlock characterization, Methods for handling deadlocks, Deadlock prevention,
Deadlock avoidance, Deadlock detection, Recovery from deadlock.

PROCESS SYNCHRONIZATION
 Process Synchronization is the coordination of execution of multiple processes in a multi-process
system to ensure that they access shared resources in a controlled and predictable manner.
 It aims to resolve the problem of race conditions and other synchronization issues in a concurrent
system.
 Race Condition
When more than one process is either running the same code or modifying the same memory or
any shared data, there is a risk that the result or value of the shared data may be incorrect because
all processes try to access and modify this shared resource. This condition is called the race
condition. To prevent race conditions, concurrent processes must be synchronized.

Example:
int shared = 5 // global variable
p1 p2
x = shared; y = shared;
x++; //6 y --; //4
sleep(1); sleep(1);
shared = x; //6 shared = y; //4

A situation like this, where several processes access and manipulate the same data concurrently and the
outcome of the execution depends on the particular order in which the access takes place, is called a race
condition.

To guard against the race condition above, we need to ensure that only one process at a time can be
manipulating the variable counter.
---------------------------------------------------------------------------------------------------------------------
THE CRITICAL-SECTION PROBLEM

 A critical section is the portion of a program that accesses shared data.


 Each process has a code segment, called critical section, in which the shared data is
accessed.
 To ensure synchronization, no two processes is should be allowed to execute in theircritical
sections at the same time.

Requirements to be satisfied for a Solution to the Critical-Section Problem:

Mutual Exclusion
 Mutual exclusion implies that only one process can be inside the critical section at any time. If
any other processes require the critical section, they must wait until it is free.

Progress
 Progress means that if a process is not using the critical section, then it should not stop any other
process from accessing it.
Bounded Waiting
 Bounded waiting means that each process must have a limited waiting time.

General structure of process Pi

do {
entry section
critical section

remainder section
exit section

} while (1);

Each process has three sections. They are


Entry section: This section contains code which is used by the processes to get permission
to enter into the critical section.
Remainder section: contains the remaining codes.
Exit section: contains code that is used by the processes to come out of the critical section.

---------------------------------------------------------------------------------------------------------------------
PERTERSON’S SOLUTION

 A classic software-based solution to the critical-section problem known as Peterson’s solution


 Peterson’s solution is restricted to two processes that alternate execution between their critical
sections and remainder sections.
 The processes are numbered Pi and Pj .
 In Peterson's solution, we have two shared variables that are used by the processes.

boolean Flag[]
The flag array is used to indicate if a process is ready to enter its critical section. For example, if flag[i] is
true, Pi is ready to enter its critical section.

int Turn:
The variable turn indicates whose turn it is to enter its critical section. For example, if turn == i, then
process Pi is allowed to execute in its critical section.
We now prove that this solution is correct. We need to show that:

1. Mutual exclusion is preserved.

2. The progress requirement is satisfied.

3. The bounded-waiting requirement is met.

 To prove property 1, we note that each Pi enters its critical section only if either flag[j] == false or
turn == i.

 To prove properties 2 and 3, we note that a process Pi can be prevented from entering the critical
section only if it is stuck in the while loop with the condition flag[j] == true and turn
== j; this loop is the only one possible. If Pj is not ready to enter the critical section, then flag[j] ==
false, and Pi can enter its critical section.
MUTEX LOCKS

 Mutex (Mutual Exclusion) lock is a simple software tool that solves the critical section
problem.
 The mutex lock is used to prevent race conditions.
 A process must acquire the lock before entering a critical section; it releases the lockwhen it
exits the critical section.
 The acquire() function acquires the lock, and the release() function releases the lock.
 A mutex lock has a boolean variable available whose value indicates if the lock is
available or not.
 If the lock is available, a call to acquire() succeeds, and the lock is then considered
unavailable.
 A process that attempts to acquire an unavailable lock is blocked until the lock isreleased.

The definition of acquire() is as follows:

acquire() {
while (!available)
; /* busy wait */
available = false;
}

Solution to the critical-section problem using mutex locks.

do {
acquire lock
critical section
release lock
remainder section
} while (true);

The definition of release() is as follows:


release() {
available = true;
}

 Calls to either acquire() or release() must be performed atomically.


 The main disadvantage of the implementation given here is that it requires busy waiting.
 mutex lock is also called a spinlock because the process “spins” while waiting for the lock tobecome
available.
 Advantage of Spinlocks is that no context switch is required when a process must wait on alock.
 When locks are expected to be held for short times, spinlocks are useful.
SEMAPHORES

 It is a synchronization tool that is used to generalize the solution to the critical section
problem.
 A Semaphore S is an integer variable that can only be accessed via two indivisible (atomic)
operations namely
1. wait or P operation ( to test )
2. signal or V operation ( to increment )

Operations on a Semaphore:

There are two primary operations on a semaphore:

1. wait (also called P or down operation):


o Decreases the value of the semaphore.
o If the semaphore value is greater than 0, the process can proceed.
o If the semaphore value is 0, the process is blocked until the semaphore value becomes
greater than 0.

wait (s)
{
while(s0);
s--;
}

2. signal (also called V or up operation):


o Increases the value of the semaphore.
o If there are processes blocked waiting for the semaphore, one of them is allowed to proceed.

signal (s)
{
s++;
}

Types of Semaphores:

1. Binary Semaphore :
o Can have only two values: 0 or 1.
o Typically used for mutual exclusion, where a semaphore of value 1 means the resource is
free, and a value of 0 means the resource is in use.
o It functions like a lock.
2. Counting Semaphore:
o Can have a value greater than 1.
o The semaphore count is the number of available resources. If the resources are added,
semaphore count automatically incremented and if the resources are removed, the count is
decremented.
Mutual Exclusion Implementation using semaphore
do
{

wait(mutex);

critical section
signal(mutex)

remainder section
} while (1);

MONITORS
 A monitor is a synchronization construct that supports mutual exclusion and the ability to
wait /block until a certain condition becomes true.
 A monitor is an abstract datatype that encapsulates data with a set of functions to operateon
the data.

Characteristics of Monitor

 The local variables of a monitor can be accessed only by the local functions.
 A function defined within a monitor can only access the local variables of a monitor and its
formal parameter.
 Only one process may be active within the monitor at a time.

Syntax of a Monitor

monitor MonitorName {

shared_variable;

procedure P1() {
// Code for P1
}

procedure P2() {
// Code for P2
}

condition c;

procedure WaitForCondition() {
if (some_condition_not_met) {
c.wait(); }
}
procedure SignalCondition() {
c.signal(); }
}
The key components of monitor syntax in process synchronization are:

Shared Variables
These are variables shared by multiple processes.

Procedures/Methods: These are the functions that manipulate the shared variables. Only one process can
execute a monitor procedure at any time, ensuring mutual exclusion.

Condition Variables: These are used for synchronization. Condition variables enable processes to wait or
signal each other when certain conditions are met.

Schematic view of a monitor

Monitor with condition variables

 Instead of lock-based protection, monitors use a shared condition variable for synchronization
and only two operations wait() and signal() can be applied on the condition variable.
condition x, y;
x.wait (); // a process that invokes the operation is suspended.
x.signal (); //resumes one of the suspended processes(if any)
-------------------------------------------------------------------------------------------------------------------
CLASSICAL PROBLEMS OF SYNCHRONIZATION

Classical problems used to test newly-proposed synchronization schemes


 Bounded-Buffer Problem
 Readers and Writers Problem
 Dining-Philosophers Problem
 Barber Shop Problem

1. Bounded-Buffer Problem

Solution for Bounded-Buffer Problem

 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.
2. Reader-Writer Problem
The Reader-Writer Problem is a classic process synchronization problem that deals with managing access
to a shared resource (such as a database or a file) by multiple readers and writers.

Challenges:
 Allow multiple readers to access the shared resource simultaneously because they only read
the data without modifying it.
 Ensure that only one writer can access the shared resource at a time to prevent data
corruption.
 Ensure that no readers can read the resource while a writer is writing.
 Make sure neither readers nor writers are indefinitely blocked.
The Dining Philosophers Problem

The Dining Philosophers Problem is a classic synchronization problem used to illustrate the challenges of avoiding
deadlock and starvation in concurrent programming.

Problem Description:

 Imagine five philosophers seated around a circular table. Each philosopher alternates between two
states: thinking and eating.
 In between each pair of philosophers is a single fork, so there are five forks in total.
 To eat, a philosopher needs both the fork to their left and the fork to their right.
 Philosophers can only use one fork at a time and must pick up both forks before eating. Once done,
they put down the forks and go back to thinking.

Example:

 Let's name the philosophers as P1, P2, P3, P4, and P5.
 P1 needs fork F1 (left) and F2 (right) to eat, P2 needs fork F2 and F3, and so on.
 If all philosophers pick up their left fork at the same time, each philosopher will be holding one fork and will
be waiting for the other one, leading to deadlock.

Solution for The Dining Philosophers Problem


3. Barber Shop Problem

The Barber Shop Problem is a classical synchronization problem in operating systems, similar to the
producer-consumer problem. It illustrates synchronization issues and is often solved using semaphores or
monitors.

Problem Overview:

In a barber shop:

 One barber provides haircuts.


 The shop has a certain number of chairs for waiting customers (let's say N chairs).
 If all the chairs are full, any new customer will leave.
 If there are available chairs, a customer sits and waits for the barber.
 If the barber is free, the customer gets a haircut.

Key Synchronization Challenges:

 If there are no customers, the barber should sleep.


 If a customer arrives and the barber is asleep, the barber needs to be woken up.
 Mutual exclusion is needed when checking/modifying the state of the waiting room (to avoid race
conditions).

Solution Using Semaphores:

1. semaphore barberReady = 0 (indicates if the barber is ready to cut hair)


2. semaphore customerReady = 0 (indicates if a customer is waiting)
3. semaphore mutex= 1 (to ensure mutual exclusion when accessing/modifying the number of
available chairs)
4. int freeSeats = N (the number of free waiting chairs)

Barber Process:
while (true)
{
wait(customerReady);
wait(mutex);
freeSeats++;
signal(barberReady);
signal(mutex);
}

Customer Process:
while (true)
{
wait(mutex);
if (freeSeats > 0) {
freeSeats--;
signal(customerReady);
signal(mutex);
wait(barberReady);
}
else {
signal(mutex);
}}
DEADLOCK

Deadlocks are a set of blocked processes each holding a resource and waiting to acquire a resource
held by another process.

Deadlock Characterization

Four Necessary conditions for a deadlock


1. Mutual exclusion: At least one resource must be held in a non sharable mode. That is only
one process at a time can use the resource. If another process requests that resource, the
requesting process must be delayed until the resource has been released.
2. Hold and wait: A process must be holding at least one resource and waiting to acquire
additional resources that are currently being held by other processes.
3. No preemption: Resources cannot be preempted.
4. Circular wait: P0 is waiting for a resource that is held by P1, P1 is waiting for a resource that
is held by P2...Pn-1.

Resource-Allocation Graph
 It is a directed graph with a set of vertices V and a set of edges E.
 V is partitioned into two types:
1. nodes P = {p1, p2,..pn}
2. Resource type R ={R1,R2,...Rm}
 Pi -->Rj - request => request edge
 Rj-->Pi - allocated => assignment edge.
 Pi is denoted as a circle and Rj as a square.
 Rj may have more than one instance represented as a dot within the square.
Sets P,R and E.
P = { P1,P2,P3}
R = {R1,R2,R3,R4}
E= {P1->R1, P2->R3, R1->P2, R2->P1, R3->P3 }
 Resource instances
One instance of resource type R1,Two instance of resource type R2,One instance
of resource type R3,Three instances of resource type R4.
Process states
Process P1 is holding an instance of resource type R2, and is waiting for an instance of resource
type R1.
Resource Allocation Graph with a deadlock

Process P2 is holding an instance of R1 and R2 and is waiting for an instance of resource type
R3.Process P3 is holding an instance of R3.
P1->R1->P2->R3->P3->R2->P1
P2->R3->P3->R2->P2
Methods for handling Deadlocks
1. Deadlock Prevention
2. Deadlock Avoidance
3. Deadlock Detection and Recovery
------------------------------------------------------------------------------------------------------------------
Deadlock Prevention:
 This ensures that the system never enters the deadlock state.
 Deadlock prevention is a set of methods for ensuring that at least one of the necessary
conditions cannot hold.
 By ensuring that at least one of these conditions cannot hold, we can prevent the
occurrence of a deadlock.
1. Denying Mutual exclusion
 Mutual exclusion condition must hold for non-sharable resources.
 Printer cannot be shared simultaneously shared by prevent processes.
 Sharable resource - example Read-only files.
 If several processes attempt to open a read-only file at the same time, they can be granted
simultaneous access to the file.
 A process never needs to wait for a sharable resource.

2. Denying Hold and wait


 Whenever a process requests a resource, it does not hold any other resource.
 One technique that can be used requires each process to request and be allocated all its
resources before it begins execution.
 Another technique is before it can request any additional resources, it must release all the
resources that it is currently allocated.
 These techniques have two main disadvantages :
o First, resource utilization may be low, since many of the resources may be
allocated but unused for a long time.
o We must request all resources at the beginning for both protocols. starvation is
possible.
3. Denying No preemption
 If a process is holding some resources and requests another resource that cannot be
immediately allocated to it. (that is the process must wait), then all resources currently
being held are preempted.
 These resources are implicitly released.
 The process will be restarted only when it can regain its old resources.
4. Denying Circular wait
 Impose a total ordering of all resource types and allow each process to request for
resources in an increasing order of enumeration.
 Let R = {R1,R2,...Rm} be the set of resource types.
 Assign to each resource type a unique integer number.
 If the set of resource types R includes tapedrives, disk drives and printers.
F(tapedrive)=1,
F(diskdrive)=5,
F(Printer)=12.
 Each process can request resources only in an increasing order of enumeration.
---------------------------------------------------------------------------------------------------------------------
Deadlock Avoidance:
 Deadlock avoidance request that the OS be given in advance additional information
concerning which resources a process will request and use during its life time. With this
information it can be decided for each request whether or not the process should wait.
 To decide whether the current request can be satisfied or must be delayed, a system must
consider the resources currently available, the resources currently allocated to each
process and future requests and releases of each process.
 Safe State
A state is safe if the system can allocate resources to each process in some order and still
avoid a dead lock.
 A deadlock is an unsafe state.
 Not all unsafe states are dead locks
 An unsafe state may lead to a dead lock
 Two algorithms are used for deadlock avoidance namely;
1. Resource Allocation Graph Algorithm - single instance of a resource type.
2. Banker’s Algorithm – several instances of a resource type.
Resource allocation graph algorithm
 Claim edge- Claim edge Pi---> Rj indicates that process Pi may request resource Rj at
some time, represented by a dashed directed edge.
 When process Pi request resource Rj, the claim edge Pi -> Rj is converted to a request
edge.
 Similarly, when a resource Rj is released by Pi the assignment edge Rj -> Pi is reconverted
to a claim edge Pi -> Rj
 The request can be granted only if converting the request edge Pi -> Rj to an assignment
edge Rj -> Pi does not form a cycle.

 If no cycle exists, then the allocation of the resource will leave the system in a safe state.
 If a cycle is found, then the allocation will put the system in an unsafe state.

Banker's algorithm
 Available: indicates the number of available resources of each type.
 Max: Max[i, j]=k then process Pi may request at most k instances of resource type Rj
 Allocation : Allocation[i. j]=k, then process Pi is currently allocated K instances of
resource type Rj
 Need : if Need[i, j]=k then process Pi may need K more instances of resource type Rj

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


Safety algorithm
1. Initialize work := available and Finish [i]:=false for i=1,2,3 .. n
2. Find an i such that both
a. Finish[i]=false
b. Needi<= Work
if no such i exists, goto step 4
3. work :=work+ allocationi;
Finish[i]:=true
goto step 2
4. If finish[i]=true for all i, then the system is in a safe state
Resource Request Algorithm
Let Requesti be the request from process Pi for resources.
1. If Requesti<= Needi goto step2, otherwise raise an error condition, since the process has
exceeded its maximum claim.
2. If Requesti<= Available, goto step3, otherwise Pi must wait, since the resources are not
available.
3. Available := Availabe-Requesti;
Allocationi := Allocationi + Requesti
Needi := Needi - Requesti;
 Now apply the safety algorithm to check whether this new state is safe or not.
 If it is safe then the request from process Pi can be granted.
-------------------------------------------------------------------------------------------------------------
Deadlock detection
(i) Single instance of each resource type
 If all resources have only a single instance, then we can define a deadlock detection
algorithm that use a variant of resource-allocation graph called a wait for graph.
Resource Allocation Graph

Wait for Graph


(ii) Several Instances of a resource type
Available : Number of available resources of each type
Allocation : number of resources of each type currently allocated to each process
Request : Current request of each process
If Request [i,j]=k, then process Pi is requesting K more instances of resource type Rj.
1. Initialize work := available
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 step4.
3. Work:=work+allocationi
Finish[i]:=true
goto step2
4. If finish[i]=false
then process Pi is deadlocked
------------------------------------------------------------------------------------------------------------------
Deadlock Recovery
1. Process Termination
1. Abort all deadlocked processes.
2. Abort one deadlocked process at a time until the deadlock cycle is eliminated.
After each process is aborted , a deadlock detection algorithm must be invoked to
determine where any process is still dead locked.
2. Resource Preemption
Preemptive some resources from process and give these resources to other processes until the
deadlock cycle is broken.
i. Selecting a victim: which resources and which process are to be preempted.
ii. Rollback: if we preempt a resource from a process it cannot continue with its normal
execution. It is missing some needed resource. we must rollback the process to some safe state,
and restart it from that state.
iii. Starvation : How can we guarantee that resources will not always be preempted from
the same process.

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