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

Unit 2 - Process Management

This document summarizes a unit on process and storage management. It covers topics like process management, process concepts, process scheduling, process states, process control blocks, context switching, process creation, process termination, and CPU scheduling algorithms. The key aspects covered are the different states a process can be in, how the operating system tracks processes using process control blocks, how processes are created and terminated, and common CPU scheduling algorithms like first-come first-served and shortest job first.

Uploaded by

ARVIND H
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)
99 views

Unit 2 - Process Management

This document summarizes a unit on process and storage management. It covers topics like process management, process concepts, process scheduling, process states, process control blocks, context switching, process creation, process termination, and CPU scheduling algorithms. The key aspects covered are the different states a process can be in, how the operating system tracks processes using process control blocks, how processes are created and terminated, and common CPU scheduling algorithms like first-come first-served and shortest job first.

Uploaded by

ARVIND H
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/ 118

Unit 2: Process and Storage Management

Module 1: Process Management


Unit 2: Processes

• Process Concept
• Process Scheduling
• Operation on Processes
• Cooperating Processes
• Interprocess Communication
Process Concept

• An operating system executes a variety of programs:


– Batch system – jobs
– Time-shared systems – user programs or tasks
• Textbook uses the terms job and process almost
interchangeably.
• Process Define:
– a program in execution; process execution must
progress in sequential fashion.
– An instance of running program
– The entity that can be assign to & execute on
processor
Process Concept
• A process includes:
– Stack: its Contains temporary data ( function,
parameters, local variables)
– Heap: dynamic allocated memory to process during runtime.
– text : Contains Global and static variable
– data section: contains PC and Contents of Processor register
• What does a process look like in memory?
Process State

• As a process executes, it changes state


– new: The process is being created.
– running: Instructions are being executed.
– waiting: The process is waiting for some event to
occur.
– ready: The process is waiting to be assigned to a
process.
– terminated: The process has finished execution.
Diagram of Process State
Process Control Block (PCB)
• PCB is a Data structure maintained by OS in every process.
• PCB identified by integer.(process ID)
• PCB keeps all the information needed to keep track of a process
Information associated with each process.
• Process state: Current state ( five state)
• Program counter: Next instruction to be executed
• CPU registers: storing for execution. ( register type)
• CPU scheduling information: process priority
• Memory-management information: information of page table or
memory limit
• Accounting information: amount of CPU real time used, time
limits, account no, process no.
• I/O status information: list of IO device allocated to process.
Process Control Block (PCB)
CPU Switch From Process to Process
Process Scheduling

• Objective of multiprogramming is :
• to have some process running at all
times, maximize CPU utilization time
• objective of time sharing is :
• To switch the CPU among processes so
frequently that users can interact with
each program while it is running
Process Scheduling Queues

• Job queue:
– Whenever a process enter the system
– set of all processes in the system.
• Ready queue – set of all processes residing in main memory,
ready and waiting to execute.
• Device queues – set of processes waiting for an I/O device.
( memory, mouse and key board
• Process migration between the various queues.
Queuing diagram Representation of
Process Scheduling
Schedulers

• Long-term scheduler (or job scheduler) –


selects which processes should be brought into
the ready queue.

• Short-term scheduler (or CPU scheduler) –


selects which process should be executed next
and allocates CPU.
Addition of Medium Term Scheduling
Schedulers (Cont.)

• Short-term scheduler \ CPU scheduler


– Select process from ready queue ( allocate from CPU)
– is invoked very frequently (milliseconds)
 (must be fast).

• Long-term scheduler / Job Sheduler


– Select process from pool ( main memory)
– invoked very infrequently (seconds, minutes)  (may
be slow).
– The long-term scheduler controls the degree of
multiprogramming.
Schedulers (Cont.)

• Processes can be described as either:


– I/O-bound process – spends more time doing I/O
request, many short CPU bursts.
– CPU-bound process – spends more time doing
computations; few very long CPU bursts.

 Medium Term scheduler


 Time sharing systems
Context Switch

• When CPU switches to another process, the system must save


the state of the old process and load the saved state for the new
process.
– State save and state restore
• Context-switch time is overhead; the system does no useful work
while switching.
• Time dependent on hardware support.
Process Creation

• Parent process creates children processes, which, in turn create


other processes, forming a tree of processes.
• Resource sharing
– Parent and children share all resources.
– Children share subset of parent’s resources.
– Parent and child share no resources.
• Execution
– Parent and children execute concurrently.
– Parent waits until children terminate.
Process Creation (Cont.)

• Address space
– Child duplicate of parent.
– Child has a program loaded into it.
• UNIX examples
– fork system call creates new process
– execve system call used after a fork to replace the process’
memory space with a new program.
Process Termination

• Process executes last statement and asks the operating system


to decide it (exit).
– Output data from child to parent (via wait).
– Process’ resources are deallocated by operating system.
• Parent may terminate execution of children processes (abort).
– Child has exceeded allocated resources.
– Task assigned to child is no longer required.
– Parent is exiting.
T Operating system does not allow child to continue if its
parent terminates.
T Cascading termination.
Cooperating Processes

• Independent process cannot affect or be affected by the


execution of another process.
• Cooperating process can affect or be affected by the execution of
another process
• Advantages of process cooperation
– Information sharing
– Computation speed-up
– Modularity
– Convenience
CPU Scheduling

• Basic Concepts
• Scheduling Criteria
• Scheduling Algorithms
• Multiple-Processor Scheduling
• Real-Time Scheduling
• Algorithm Evaluation

Operating System Concepts


Basic Concepts

• Maximum CPU utilization obtained with multiprogramming


• I/O Burst phase: – when the process waits for some IO
operation
– Process execution consists of a cycle of CPU execution and I/O
wait.

• CPU burst phase :distribution or when the process is allocated


CPU and other resource is executing

Operating System Concepts


Alternating Sequence of CPU And I/O Bursts

Operating System Concepts


CPU Scheduler
• Selects from among the processes in memory that are ready to
execute, and allocates the CPU to one of them.
• CPU scheduling decisions may take place when a process:
1. Switches from running to waiting state.( I/O wait)
2. Switches from running to ready state.( Interrupt)
3. Switches from waiting to ready.(IO complete)
4. Process terminates.
Scheduling under 1 and 4 is nonpreemptive.
• Nonpreemptive: there is no choice for CPU scheduling ( Stop)
– Terminate or waiting state
– new process present in queue.
• All other scheduling is preemptive
– Process has choice CPU scheduling and CPU is execute
based on the priority.

Operating System Concepts


Dispatcher

• Dispatcher module gives control of the CPU to the process


selected by the short-term scheduler; this functionality involves:
– switching context: switching from one process to another
process
– switching to user mode: switching to kernel mode to user
mode
– jumping to the proper location in the user program to
restart that program
• Dispatch latency – time it takes to stop one process and start
another running process.

Operating System Concepts


Scheduling Criteria

• CPU utilization – keep the CPU as busy as possible


• Throughput – # of processes that complete their execution per
time unit
• Turnaround time – amount of time to execute a particular process
• Waiting time – amount of time a process has been waiting in the
ready queue
• Response time – amount of time it takes from when a request
was submitted until the first response is produced, not output
(for time-sharing environment)

Operating System Concepts


Optimization Criteria

• Max CPU utilization


• Max throughput
• Min turnaround time
• Min waiting time
• Min response time

Operating System Concepts


Scheduling Algorithms

 First In First Out (FIFO)


 Shortest Job first (SJF)
 Round Robin (RR)
 Multilevel Queue
 Multilevel Feedback

Operating System Concepts


FCFS: First Come First Serve

• First Come First Serve, is just like FIFO(First in First out) Queue
data structure, where the data element which is added to the
queue first, is the one who leaves the queue first.
• This is used in Batch Systems.
• It's easy to understand and implement programmatically, using
a Queue data structure, where a new process enters through
the tail of the queue, and the scheduler selects process from
the head of the queue.
• A perfect real life example of FCFS scheduling is buying tickets
at ticket counter.
• Burst time: the time CPU taking control of process

Operating System Concepts


First-Come, First-Served (FCFS) Scheduling

• Example: Process Burst Time


P1 24
P2 3
P3 3
• Suppose that the processes arrive in the order: P1 , P2 , P3
The Gantt Chart for the schedule is:

P1 P2 P3

0 24 27 30
• Waiting time for P1 = 0; P2 = 24; P3 = 27
• Average waiting time: (0 + 24 + 27)/3 = 17

Operating System Concepts


FCFS Scheduling (Cont.)

Suppose that the processes will arrive in the order


P2 , P3 , P1 .
• The Gantt chart for the schedule is:

P2 P3 P1

0 3 6 30

• Waiting time for P1 = 6; P2 = 0; P3 = 3


• Average waiting time: (6 + 0 + 3)/3 = 3
• Much better than previous case.
• Convoy effect short process behind long process

Operating System Concepts


FCFS

• Problems:
1. It is non-preemptive
2. Improper process Scheduling
3. Resource unitization in parallel is not possible, which
leads to convey effect and hence poor resource
utilization
– convey effect: in which whole os slows down due to few slow
process.

Operating System Concepts


Shortest-Job-First (SJF) Scheduling

• It is the best approach to minimize waiting time.


• It select the waiting process with the smallest
execution time to execute next.

Operating System Concepts


Shortest-Job-First (SJF) Scheduling

• Associate with each process the length of its next CPU burst.
Use these lengths to schedule the process with the shortest time.
• Two schemes:
– nonpreemptive – once CPU given to the process it cannot
be preempted until completes its CPU burst.
– Preemptive – if a new process arrives with CPU burst length
less than remaining time of current executing process,
preempt. This scheme is know as the
Shortest-Remaining-Time-First (SRTF).
• SJF is optimal – gives minimum average waiting time for a given
set of processes.

Operating System Concepts


Operating System Concepts
Disadvantage:

The total execution time of job must be known before


execution while it is not possible to perfectly predict
execution

Operating System Concepts


Operating System Concepts
Shortest-Remaining-Time-First (SRTF).
• As you can see in the GANTT chart above, as P1 arrives first,
hence it's execution starts immediately, but just after 1 ms,
process P2 arrives with a burst time of 3 ms which is less than
the burst time of P1, hence the process P1(1 ms done, 20 ms
left) is preemptied and process P2 is executed.
• As P2 is getting executed, after 1 ms, P3 arrives, but it has a
burst time greater than that of P2, hence execution of P2
continues. But after another millisecond, P4 arrives with a burst
time of 2 ms, as a result P2(2 ms done, 1 ms left) is preemptied
and P4 is executed.
• After the completion of P4, process P2 is picked up and finishes,
then P2 will get executed and at last P1.
• The Pre-emptive SJF is also known as Shortest Remaining
Time First, because at any given point of time, the job with the
shortest remaining time is executed first.

Operating System Concepts


Example of Non-Preemptive SJF

Process Arrival Time Burst Time


P1 0.0 7
P2 2.0 4
P3 4.0 1
P4 5.0 4
• SJF (non-preemptive)

P1 P3 P2 P4

0 3 7 8 12 16

• Average waiting time = (0 + 6 + 3 + 7)/4 - 4

Operating System Concepts


Example of Preemptive SJF

Process Arrival Time Burst Time


P1 0.0 7
P2 2.0 4
P3 4.0 1
P4 5.0 4
• SJF (preemptive)

P1 P2 P3 P2 P4 P1

0 2 4 5 7 11 16

• Average waiting time = (9 + 1 + 0 +2)/4 - 3

Operating System Concepts


Priority Scheduling

• A priority number (integer) is associated with each process


• The CPU is allocated to the process with the highest priority
(smallest integer  highest priority).
– Preemptive
– nonpreemptive
• SJF is a priority scheduling where priority is the predicted next
CPU burst time.
• Problem  Starvation – low priority processes may never
execute.
• Solution  Aging – as time progresses increase the priority of the
process.

Operating System Concepts


Round Robin (RR)

• Each process gets a small unit of CPU time (time quantum),


usually 10-100 milliseconds. After this time has elapsed, the
process is preempted and added to the end of the ready queue.
• If there are n processes in the ready queue and the time
quantum is q, then each process gets 1/n of the CPU time in
chunks of at most q time units at once. No process waits more
than (n-1)q time units.
• Performance
– q large  FIFO
– q small  q must be large with respect to context switch,
otherwise overhead is too high.

Operating System Concepts


Example: RR with Time Quantum = 20

Process Burst Time


P1 53
P2 17
P3 68
P4 24
• The Gantt chart is:

P1 P2 P3 P4 P1 P3 P4 P1 P3 P3

0 20 37 57 77 97 117 121 134 154 162

• Typically, higher average turnaround than SJF, but better


response.

Operating System Concepts


Round robin (RR)

• It is designed especially for time sharing systems.


• It is similar to FCFS scheduling, but preemption is added
to switch between process.
• Round Robin is the preemptive process scheduling
algorithm.
• Each process is provided a fix time to execute, it is called
a time quantum or time slice.
• Once a process is executed for a given time period, it is
preempted and other process executes for a given time
period.
• Context switching is used to save states of preempted
processes.

Operating System Concepts


P1=6, p2=5, p3=2, p4=3,p5=7

Operating System Concepts


Multilevel Queue

• Ready queue is partitioned into separate queues:


foreground (interactive)
background (batch)
• Each queue has its own scheduling algorithm,
foreground – RR
background – FCFS
• Scheduling must be done between the queues.
– Fixed priority scheduling; i.e., serve all from foreground then
from background. Possibility of starvation.
– Time slice – each queue gets a certain amount of CPU time
which it can schedule amongst its processes; i.e.,
- 80% to foreground in RR
- 20% to background in FCFS

Operating System Concepts


Multilevel Queue Scheduling

Operating System Concepts


Multilevel Feedback Queue

• A process can move between the various queues; aging can be


implemented this way.
• Multilevel-feedback-queue scheduler defined by the following
parameters:
– number of queues
– scheduling algorithms for each queue
– method used to determine when to upgrade a process
– method used to determine when to demote a process
– method used to determine which queue a process will enter
when that process needs service

Operating System Concepts


Multilevel Feedback Queues

Operating System Concepts


Example of Multilevel Feedback Queue

• Three queues:
– Q0 – FCFS
– Q1 – time quantum 8 milliseconds
– Q2- time quantum 16 milliseconds
• Scheduling
– A new job enters queue Q0 which is served FCFS. When it
gains CPU, job receives 8 milliseconds. If it does not finish
in 8 milliseconds, job is moved to queue Q1.
– At Q1 job is again served FCFS and receives 16 additional
milliseconds. If it still does not complete, it is preempted
and moved to queue Q2.
Process Synchronization

• Background
• The Critical-Section Problem
• Synchronization Hardware
• Semaphores
• Classical Problems of Synchronization
• Critical Regions
• Monitors

Operating System Concepts


Process Synchronization
• Process Synchronization means sharing
system resources by processes in a such a way
that, Concurrent access to shared data is
handled thereby minimizing the chance of
inconsistent data. Maintaining data consistency
demands mechanisms to
ensure synchronized execution of
cooperating processes.

Operating System Concepts


Background

• Concurrent access to shared data may result in data


inconsistency.
• Maintaining data consistency requires mechanisms to ensure the
orderly execution of cooperating processes.
• Process Synchronization is divided into two types:
• Independent process: execution of one process does not
affects the executes of other.
• Cooperating process: execution of one process affects the
executes of other. ( concurrent access)
• Code segment  shared variables: p1,p2,p3

Operating System Concepts


The Critical-Section Problem

• n processes all competing to use some shared data


• Each process has a code segment, called critical section, in
which the shared data is accessed.
• Problem – ensure that when one process is executing in its
critical section, no other process is allowed to execute in its
critical section.
• Structure of process Pi
repeat
entry section
critical section
exit section
reminder section
until false;

Operating System Concepts


Solution to Critical-Section Problem
Must satisfy the following three conditions:
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. 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.

Operating System Concepts


Initial Attempts to Solve Problem

• Only 2 processes, P0 and P1


• General structure of process Pi (other process Pj)
repeat
entry section
critical section
exit section
reminder section
until false;
• Processes may share some common variables to synchronize
their actions.

Operating System Concepts


Synchronization Hardware
• Many system provide h/w support for this C.S code

• Uniprocessor :
– could disable interrupts
– Currently running code would execute without preemption.
– Generally too inefficient on multi processor system
 Modern machine provide special atomic h/w instruction
 Atomic – non interruptible
- either test memory word & set value
- Or Swap contents of two memory words

• Test and modify the content of a word atomically.


function Test-and-Set (var target: boolean): boolean;
begin
Test-and-Set := target;
target := true;
end;
Operating System Concepts
Methods to implement process
synchronization

• Mutual Exclusion (Mutex)


Mutex or Mutual Exclusion Object is used to give access to a resource to only one
process at a time. The mutex object allows all the processes to use the same
resource but at a time, only one process is allowed to use the resource. Mutex uses
the lock-based technique to handle the critical section problem.

• Semaphore
Semaphore is an integer variable S, that is initialized with the number of resources
present in the system and is used for process synchronization. It uses two functions
to change the value of S i.e. wait() and signal(). Both these functions are used to
modify the value of semaphore but the functions allow only one process to change
the value at a particular time i.e. no two processes can change the value of
semaphore simultaneously. There are two categories of semaphores i.e. Counting
semaphores and Binary semaphores.

Operating System Concepts


Mutual Exclusion with Test-and-Set

• Shared data: var lock: boolean (initially false)


• Process Pi
repeat
while Test-and-Set (lock) do no-op;
critical section
lock := false;
remainder section
until false;

Operating System Concepts


Semaphore
• Synchronization tool that represents data structures used by the OS kernel to
synchronize processors.
• does not require busy waiting.
• It is a type of generalized lock.
• Semaphore S – consist of a positive integer variable accessed through 2 std atomic
operations.
• Two atomic operations:
– Wait: originally termed as P ( proberen – meaning test in dutch). It decrements
the semaphore value. If the value becomes negative, then the process executing
the wait() is blocked.
– Signal: increments the value of semaphore S by 1. If the value is not positive ,
then a process blocked by a wait () operation is unblocked.
• can only be accessed via two indivisible (atomic) operations
wait (S): { while S 0 do no-op;
S := S – 1; }
signal (S): S := S + 1;
Wait() and Signal() operations must be executed individually. When one process
modifies the semaphore value, no other process can modify the same semaphore
value simultaneously.
Operating System Concepts
Counting semaphores

• In Counting semaphores, the value can range over an unrestricted


domain. Used to control access to a given resource containing a finite
number of instances.
• First the semaphore is initialized equal to the number of resources
available.
• Each process wanting to use a resource performs a wait() operation on
the semaphore by decrementing the count.
• When a process releases a resource , it performs a signal() operation on
the semaphore by incrementing the count.
• When the count for semaphore becomes o, all resources are in use.
Therefore processes wishing to use a resource will block until the count
becomes greater than 0.

Operating System Concepts


Binary semaphore

• In Binary semaphores, the value of the semaphore variable will be 0 or


1. It is also known as mutex locks(Mutual Exclusion).
• Initially, the value of semaphore variable is set to 1 and if some process
wants to use some resource then the wait() function is called and the
value of the semaphore is changed from 1 to 0.
• The process then uses the resource and when it releases the resource
then the signal() function is called and the value of the semaphore
variable is increased to 1.
• If at a particular instant of time, the value of the semaphore variable is 0
and some other process wants to use the same resource then it has to
wait for the release of the resource by the previous process.
• In this way, process synchronization can be achieved.

Operating System Concepts


Example: Critical Section of n Processes

• Shared variables
– var mutex : semaphore
– initially mutex = 1
• Process Pi
repeat
wait(mutex);
critical section
signal(mutex);
remainder section
until false;

Operating System Concepts


Semaphore as General Synchronization Tool

• Execute B in Pj only after A executed in Pi


• Use semaphore flag initialized to 0
• Code:
Pi Pj
 
A wait(flag)
signal(flag) B

Operating System Concepts


Deadlock and Starvation

• Deadlock – two or more processes are waiting indefinitely for an


event that can be caused by only one of the waiting processes.
• Let S and Q be two semaphores initialized to 1
P0 P1
wait(S); wait(Q);
wait(Q); wait(S);
 
signal(S); signal(Q);
signal(Q) signal(S);
• Starvation – indefinite blocking. A process may never be
removed from the semaphore queue in which it is suspended.

Operating System Concepts


Disadvanage

• Busy waiting: the continual looping


of semaphore process
• Spinlock: when the busy waiting
happen and it waste CPU cycles.

Operating System Concepts


Classical Problems of Synchronization

• Producer-Consumer (Bounded-Buffer) Problem


• Readers - Writers Problem
• Dining-Philosophers Problem
– Those problem can be solved by using semaphore variables

Bounded-Buffer Problem
– N buffer , each can hold one item.
– Constraints : full :=0; empty := n; mutex :=1;

Operating System Concepts


Producer-consumer problem
(Bounded buffer)
• Classical example of a multi-prosess synchronization problem.
• Describes 2 processes : Producer , consumer who shares a common fixed size
buffer
• Producer job – generate a piece of data and put in the buffer and start again.
• At the same time the consumer is consuming the data ,(removing it from the buffer)
one piece at a time.
• The problem is to make sure that the producer wont try to add data into the buffer it
is full and the consumer wont try to remove from an empty buffer.
• Solution for producer is to goto sleep if the buffer is FULL. (THE NEXT TIME THE
CONSUMER REMOVES AN ITEM FROM BUFFER , IT WAKES UP THE
PRODUCER WHO STARTS TO FILL THE BUFFER AGAIN)
• The consumer goes to sleep if the buffer is EMPTY. ((THE NEXT TIME THE
PRODUCER PUTS DATA INTO THE BUFFER , IT WAKES UP THE SLEEPING
CUSTOMER)
• The solution can be reached using semaphore, inadequate solution may lead to
Deadlock where both the processes are waiting to be awakend.

Operating System Concepts


Bounded-Buffer Problem with race condition
Int Itemcount=0; Void consumer()
Void producer() {
{ while (true)
While (true) {
{ if(ItemCount == 0)
item=produce_item(); sleep();
if(Itemcount == BUFFER_SIZE) item=removeItemFromBuffer();
sleep(); ItemCount--;
PutItemIntoBuffer(item); if(ItemCount == BUFFER_SIZE-1)
Itemcount=ItemCount+1; wakeup(producer);
If(Itemcount == 1) Consume_item(item);
Wakeup(consumer); }
} }
}
Race Condition:
Several processes access and manipulate the same data concurrently and the result of execution depends
on the particular order in which the access takes place.
Bounded-Buffer Problem solution
using semaphore
Semaphore mutex=1; Void consumer()
Semaphore full=0; {
Semaphore empty= BUFFER_SIZE; while(true)
Void producer() {
{ wait(full);
while(true) wait(mutex);
{ item=removeItemFromBuffer();
item=produce_item(); signal(mutex);
wait(empty); signal(empty);
wait(mutex); consume_item(item);
putItemIntoBuffer(item); }
signal(mutex); }
signal(full);
}
}
Readers-Writers Problem

• Reader: onlyread the data set they do not


perform any updates
• Writer: 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 a time

Operating System Concepts


Readers-Writers Problem

• Shared data
var mutex, wrt: semaphore (=1);
readcount : integer (=0);

• Writer process
wait(wrt);

writing is performed

signal(wrt);

Operating System Concepts


Readers-Writers Problem (Cont.)

• Reader process
wait(mutex);
readcount := readcount +1;
if readcount = 1 then wait(wrt);
signal(mutex);

reading is performed

wait(mutex);
readcount := readcount – 1;
if readcount = 0 then signal(wrt);
signal(mutex):

Operating System Concepts


Dining-Philosophers Problem

• Shared data
var chopstick: array [0..4] of semaphore;
(=1 initially)

Operating System Concepts


Dining-Philosophers Problem
• 5 philosopher are sitting around a circular table.
• Dinning table has 5 chopsticks and bowl of rice in
the middle
• Philosopher either eat and think
• When philosopher want to eat, he use & chopsticks.
• He keeps down both chopsticks
• Problem: deadlock

Operating System Concepts


Dining-Philosophers Problem (Cont.)

• Philosopher i:
repeat
wait(chopstick[i])
wait(chopstick[i+1 mod 5])

eat

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

think

until false;

Operating System Concepts


Critical Regions

• High-level synchronization construct


• A shared variable v of type T, is declared as:
var v: shared T
• Variable v accessed only inside statement
region v when B do S

where B is a Boolean expression.


While statement S is being executed, no other process can
access variable v.

Operating System Concepts


Dining Philosophers Example
type dining-philosophers = monitor
var state : array [0..4] of :(thinking, hungry, eating);
var self : array [0..4] of condition;
procedure entry pickup (i: 0..4);
begin
state[i] := hungry,
test (i);
if state[i]  eating then self[i], wait,
end;

procedure entry putdown (i: 0..4);


begin
state[i] := thinking;
test (i+4 mod 5);
test (i+1 mod 5);
end;

Operating System Concepts


Dining Philosophers (Cont.)
procedure test(k: 0..4);
begin
if state[k+4 mod 5]  eating
and state[k] = hungry
and state[k+1 mod 5] ]  eating
then begin
state[k] := eating;
self[k].signal;
end;

end;

begin
for i := 0 to 4
do state[i] := thinking;
end.
Operating System Concepts
Process Managent: Deadlocks

• System Model
• Deadlock Characterization
• Methods for Handling Deadlocks
• Deadlock Prevention
• Deadlock Avoidance
• Deadlock Detection
• Recovery from Deadlock
• Combined Approach to Deadlock Handling

Operating System Concepts


The Deadlock Problem
• A set of blocked processes each holding a resource and waiting
to acquire a resource held by another process in the set.
• It is a situation when 2 process sharing the same resources are
effectively preventing each other from accessing the resources.
• Example: phone call to and from
• Example
– System has 2 tape drives.
– P1 and P2 each hold one tape drive and each needs another
one.
• Example
– semaphores A and B, initialized to 1

P0 P1
wait (A); wait(B)
wait (B); wait(A)
Bridge Crossing Example

• Traffic only in one direction.


• Each section of a bridge can be viewed as a resource.
• If a deadlock occurs, it can be resolved if one car backs up
(preempt resources and rollback).
• Several cars may have to be backed up if a deadlock occurs.
• Starvation is possible.

Operating System Concepts


System Model
• A system consists of a finite number of resources which must ne
distributed among a number of competing processes.
• Resource types R1, R2, . . ., Rm
CPU cycles, memory space, I/O devices
• Each resource type Ri has Wi instances.
• Types of resources : Pre-emptable resource (memory)
Non pre-emptable resources (printing on progress)
• Can be physical resources ( printers, tape drives, memory space)
• Can be logical resources (files, semaphores ,monitors)
• Each process utilizes a resource as follows:
– request
– use
– release

Operating System Concepts


Deadlock Characterization-Necessary
conditions, Resource Allocation Graph
Deadlock can arise if four Necessary conditions hold simultaneously.
• Mutual exclusion: only one process at a time can use a resource. Not sharable. Other
process needs to wait.
• 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: (Hold and Wait) there exists a set {P0, P1, …, P0} 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 P0 is waiting for a resource that is
held by P0.

Operating System Concepts


Resource-Allocation Graph (RAG)

Directed graph
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 P1  Rj
• assignment edge – directed edge Rj  Pi

Operating System Concepts


Resource-Allocation Graph (Cont.)

• Process

• Resource Type with 4 instances

• Pi requests instance of Rj

Pi
Rj
• Pi is holding an instance of Rj

Pi
Rj

Operating System Concepts


Example of a Resource Allocation Graph

Operating System Concepts


Resource Allocation Graph With A Deadlock

Operating System Concepts


Resource Allocation Graph With A Cycle But No Deadlock

Operating System Concepts


Basic Facts

• If graph contains no cycles  no deadlock.


• If graph contains a cycle 
– if only one instance per resource type, then deadlock.
– if several instances per resource type, possibility of
deadlock.

Operating System Concepts


Methods for Handling Deadlocks

• Ensure that the system will never enter a deadlock state-


Deadlock Prevention
• Allow the system to enter a deadlock state and then recover.-
Deadlock Detection and Recovery
• Dynamic avoidance by careful allocation of resources-Deadlock
avoidance
• Ignore the problem and pretend that deadlocks never occur in the
system; used by most operating systems, including UNIX.

Operating System Concepts


Deadlock Prevention

Restrain the ways request can be made.


• Mutual Exclusion – not required for sharable resources; must
hold for nonsharable 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.
– Low resource utilization; starvation possible.

Operating System Concepts


Deadlock Prevention (Cont.)

• 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.
• Circular Wait – impose a total ordering of all resource types, and
require that each process requests resources in an increasing
order of enumeration.

Operating System Concepts


Deadlock Avoidance
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.

Operating System Concepts


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 safe sequence of all
processes.
• Sequence <P1, P2, …, Pn> is safe if 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.
– 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.

Operating System Concepts


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.

Operating System Concepts


Safe, unsafe , deadlock state spaces

Operating System Concepts


Resource-Allocation Graph Algorithm

• 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.
• When a resource is released by a process, assignment edge
reconverts to a claim edge.
• Resources must be claimed a priori in the system.

Operating System Concepts


Resource-Allocation Graph For Deadlock Avoidance

Operating System Concepts


Unsafe State In A Resource-Allocation Graph

Operating System Concepts


Banker’s Algorithm

• 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.

Operating System Concepts


Operating System Concepts
Operating System Concepts
Data Structures for the Banker’s Algorithm

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].

Operating System Concepts


Safety Algorithm
1.Let n= no:of process and m=no: of resources ,Max[n][m],Allocation[n][m] and
Need[n][m] are the matrices of the order n * m
Available[m], Temp[m] and Done[n] are vectors of length m, m and n respectively.

2. Initialize Temp[j] =Available[j] for all j. and Done[i]=false for all i.


3. Find an i such that
(a) Done [i] == false
(b) Need[i][j]  Temp[j]
If no such i exists, go to step 5.
3. Temp[i] = Temp[j] + Allocation[i][j] for all j.
Done[i] := true
go to step 3.
4. If Done [i] == true for all i, then the system is in a safe state.

Operating System Concepts


Resource-Request Algorithm for Process Pi
1. Let Requesti and Needi be the request vector and need vector
for the process Pi .when a request for resources is made by Pi
the following actions are taken.
2. If Requesti  Needi go to step 3. Otherwise, raise error
condition, since process has exceeded its maximum claim.
3. If Requesti  Available, go to step 4. Otherwise Pi must wait,
since resources are not available.
4. Pretend 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 Pi.
• If unsafe  Pi must wait, and the old resource-allocation
state is restored

Operating System Concepts


BANKER’S ALGORITHM EXAMPLE

Operating System Concepts


Operating System Concepts
Deadlock Detection

• Allow system to enter deadlock state


• Detection algorithm
• Recovery scheme

Operating System Concepts


Single Instance of Each Resource Type

• Maintain wait-for graph


– Nodes are processes.
– Pi  Pj if Pi is waiting for Pj.
• Periodically invoke an algorithm that searches for acycle in the
graph.
• 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.

Operating System Concepts


Resource-Allocation Graph And Wait-for Graph

Resource-Allocation Graph Corresponding wait-for graph

Operating System Concepts


Several Instances of a Resource Type

• 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 [ij] = k, then process Pi is requesting k more
instances of resource type. Rj.

Let n=no: of process and m=no: of resources

Operating System Concepts


Detection Algorithm
1. Let n= no:of process and m=no: of resources Allocation[n][m]
and Request[n][m] are the matrices of the order n * m
Available[m], Temp[m] and Done[n] are vectors of length m, m and
n respectively.
2. Initialize Temp[j] =Available[j] for all j. and If Allocationi == 0 then
Done[i]=true else Done[i]=false
3. Find an i such that
(a) Done [i] == false
(b) Reques[i][j]  Temp[j]
If no such i exists, go to step 5.
4. Temp[i] = Temp[j] + Allocation[i][j] for all j.
Done[i] := true
go to step 3.
5. If Done [i] == false for some i, then the system is in deadlocked
state and process Pi is deadlocked.

Operating System Concepts


Detection-Algorithm Usage

• When, and how often, to invoke depends on:


– How often a deadlock is likely to occur?
– How many processes will need to be rolled back?
 one for each disjoint cycle

• If detection algorithm is invoked arbitrarily, there may be many


cycles in the resource graph and so we would not be able to tell
which of the many deadlocked processes “caused” the deadlock.

Operating System Concepts


Recovery from Deadlock: Process Termination

• 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?

Operating System Concepts


Recovery from Deadlock: Resource Preemption

• Selecting a victim – minimize cost.


• Rollback – return to some safe state, restart process fro that
state.
• Starvation – same process may always be picked as victim,
include number of rollback in cost factor.

Operating System Concepts


Combined Approach to Deadlock Handling

• Combine the three basic approaches


– prevention
– avoidance
– detection
allowing the use of the optimal approach for each of resources in
the system.
• Partition resources into hierarchically ordered classes.
• Use most appropriate technique for handling deadlocks within
each class.

Operating System Concepts

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