OS_UNIT_2_2020

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 53

CPU Scheduling

CPU Scheduling
Basic Concepts
Scheduling Criteria
Scheduling Algorithms
Multiple-Processor Scheduling
Real-Time Scheduling
Basic Concepts
Maximum CPU utilization obtained with
multiprogramming
CPU–I/O Burst Cycle – Process
execution consists of a cycle of CPU
execution and I/O wait
CPU burst distribution
Alternating Sequence of CPU And I/O Bursts
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
2. Switches from running to ready state
3. Switches from waiting to ready
4. Terminates
Scheduling under 1 and 4 is nonpreemptive
All other scheduling is preemptive
Dispatcher
Dispatcher module gives control of the
CPU to the process selected by the
short-term scheduler; this involves:
switching context
switching to user mode
jumping to the proper location in the user
program to restart that program
Dispatch latency – time it takes for the
dispatcher to stop one process and start
another running
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)
Optimization Criteria
Max CPU utilization
Max throughput
Min turnaround time
Min waiting time
Min response time
First-Come, First-Served (FCFS) Scheduling

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
FCFS Scheduling (Cont.)
Suppose that the processes 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
Shortest-Job-First (SJR) 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
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 =


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


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
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
Example of 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
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
Multilevel Queue Scheduling
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
Example of Multilevel
Feedback Queue
Three queues:
Q0 – RR with time quantum 8 milliseconds
Q1 – RR time quantum 16 milliseconds
Q2 – FCFS
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
Multilevel Feedback Queues
Multiple-Processor Scheduling
CPU scheduling more complex
when multiple CPUs are available
Homogeneous processors within a
multiprocessor
Load sharing
Asymmetric multiprocessing –
only one processor accesses the
system data structures, alleviating
the need for data sharing
Real-Time Scheduling
Hard real-time systems –
required to complete a critical
task within a guaranteed
amount of time
Soft real-time computing –
requires that critical processes
receive priority over less
fortunate ones
Thread Scheduling
Local Scheduling – How the threads
library decides which thread to put
onto an available LWP

Global Scheduling – How the kernel


decides which kernel thread to run
next
Process Synchronization
Process Synchronization
Background
The Critical-Section Problem
Peterson’s Solution
Synchronization Hardware
Semaphores
Classic Problems of
Synchronization
Monitors
Synchronization Examples
Atomic Transactions
Background
Concurrent access to shared data may
result in data inconsistency
Maintaining data consistency requires
mechanisms to ensure the orderly
execution of cooperating processes
Suppose that we wanted to provide a
solution to the consumer-producer
problem that fills all the buffers. We can
do so by having an integer count that
keeps track of the number of full buffers.
Initially, count is set to 0. It is
incremented by the producer after it
produces a new buffer and is
decremented by the consumer after it
Producer
while (true) {

/* produce an item and put in


nextProduced */
while (count == BUFFER_SIZE)
; // do nothing
buffer [in] = nextProduced;
in = (in + 1) %
BUFFER_SIZE;
count++;
}
Consumer
while (true) {
while (count == 0)
; // do nothing
nextConsumed =
buffer[out];
out = (out + 1) %
BUFFER_SIZE;
count--;

/* consume the item in


nextConsumed
}
Race Condition
 count++ could be implemented as

register1 = count
register1 = register1 + 1
count = register1
 count-- could be implemented as

register2 = count
register2 = register2 - 1
count = register2
 Consider this execution interleaving with “count = 5” initially:

S0: producer execute register1 = count


{register1 = 5}
S1: producer execute register1 = register1 + 1
{register1 = 6}
S2: consumer execute register2 = count
{register2 = 5}
S3: consumer execute register2 = register2 - 1
{register2 = 4}
S4: producer execute count = register1 {count
=6}
Solution to Critical-Section
Problem
1. Mutual Exclusion - If process P is executing
i
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
Peterson’s Solution
Two process solution
Assume that the LOAD and STORE
instructions are atomic; that is,
cannot be interrupted.
The two processes share two
variables:
int turn;
Boolean flag[2]
The variable turn indicates whose
turn it is to enter the critical
section.
The flag array is used to indicate if
a process is ready to enter the
critical section. flag[i] = true
Algorithm for Process Pi
while (true) {
flag[i] = TRUE;
turn = j;
while ( flag[j] && turn == j);

CRITICAL SECTION

flag[i] = FALSE;

REMAINDER SECTION

}
Synchronization Hardware
Many systems provide hardware
support for critical section code
Uniprocessors – could disable
interrupts
Currently running code would
execute without preemption
Generally too inefficient on
multiprocessor systems
 Operating systems using this not
broadly scalable
Modern machines provide special
atomic hardware instructions
 Atomic = non-interruptable
Either test memory word and set
value
Semaphore
 Synchronization tool that does not require busy waiting
 Semaphore S – integer variable
 Two standard operations modify S: wait() and signal()
Originally called P() and V()
 Less complicated
 Can only be accessed via two indivisible (atomic) operations
wait (S) {
while S <= 0
; // no-op
S--;
}
signal (S) {
S++;
}
Semaphore as General Synchronization Tool
Counting semaphore – integer value can
range over an unrestricted domain
Binary semaphore – integer value can range
only between 0
and 1; can be simpler to implement
Also known as mutex locks
Can implement a counting semaphore S as a
binary semaphore
Provides mutual exclusion
Semaphore S; // initialized to 1
wait (S);
Critical Section
signal (S);
Semaphore Implementation
Must guarantee that no two
processes can execute wait () and
signal () on the same semaphore at
the same time
Thus, implementation becomes the
critical section problem where the
wait and signal code are placed in the
crtical section.
Could now have busy waiting in
critical section implementation
 But implementation code is short
 Little busy waiting if critical section rarely

occupied
Note that applications may spend lots
of time in critical sections and
Semaphore Implementation with no Busy waiting

With each semaphore there is an


associated waiting queue. Each entry
in a waiting queue has two data items:
 value (of type integer)
 pointer to next record in the list

Two operations:
block – place the process invoking the
operation on the appropriate
waiting queue.
wakeup – remove one of processes in
the waiting queue and place it in the
ready queue.
Semaphore Implementation with no Busy waiting (Cont.)

 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); }
}
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.
Classical Problems of
Synchronization
Bounded-Buffer Problem
Readers and Writers Problem
Dining-Philosophers Problem
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.
Bounded Buffer Problem
(Cont.)
 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);
}
Bounded Buffer Problem
(Cont.)
 The structure of the consumer process

while (true) {
wait (full);
wait (mutex);

// remove an item from buffer

signal (mutex);
signal (empty);

// consume the removed item

}
Readers-Writers

Problem
A data set is shared among a number of
concurrent processes
 Readers – only read the data set; they do not
perform any updates
 Writers – can both read and write.

Problem – allow multiple readers to read


at the same time. Only one single writer
can access the shared data at the same
time.

Shared Data
 Data set
 Semaphore mutex initialized to 1.
 Semaphore wrt initialized to 1.
Readers-Writers Problem
(Cont.)
The structure of a writer process

while (true) {
wait (wrt) ;

// writing is performed

signal (wrt) ;
}
Readers-Writers Problem
(Cont.)
 The structure of a reader process

while (true) {
wait (mutex) ;
readcount ++ ;
if (readcount == 1) wait (wrt) ;
signal (mutex)

// reading is performed

wait (mutex) ;
readcount - - ;
if (readcount == 0) signal (wrt) ;
signal (mutex) ;
}
Dining-Philosophers Problem

Shared data
Bowl of rice (data set)
 Semaphore chopstick [5] initialized to 1
Dining-Philosophers Problem
(Cont.)
 The structure of Philosopher i:

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

// eat

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

// think

}
Problems with Semaphores
 Incorrect use of semaphore
operations:

 signal (mutex) …. wait (mutex)

 wait (mutex) … wait (mutex)

 Omitting of wait (mutex) or signal


(mutex) (or both)
Monitors
 A high-level abstraction that provides a
convenient and effective mechanism for process
synchronization
 Only one process may be active within the
monitor at a time

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

procedure Pn (…) {……}

Initialization code ( ….) { … }



}
Schematic view of a Monitor
Monitor with Condition Variables

You might also like