SDC 2.2 2.3 Scheduling Algorithms
SDC 2.2 2.3 Scheduling Algorithms
• Throughput –
– No of processes that complete their execution per time unit
• Turnaround time –
– amount of time to execute a particular process
– The interval from the time of submission of a process to the
time of completion.
Scheduling Criteria
• Waiting time –
– amount of time a process has been waiting in the ready
queue/ Sum of periods spent waiting in 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)
Scheduling Algorithm Optimization Criteria
4) Terminates
CPU Scheduler
• Scheduling under 1 and 4 is nonpreemptive
– once the CPU has been allocated to a process, the process keeps
the CPU until it releases the CPU either by terminating or by
switching to the waiting state.
• SJF is optimal –
– gives minimum average waiting time for a given set of processes
Shortest-Job-First (SJF) Scheduling
• Two schemes:
– Non-preemptive
– preemptive – Also known as the
Shortest-Remaining-Time-First (SRTF).
• SRTF is optimal
– if the processes may arrive at different times
Example of Non-preemptive SJF
ProcessArriva leBurst Time
P1 0.0 6
P2 2.0 8
P3 4.0 7
P4 5.0 3
P4 P1 P3 P2
0 3 9 16 24
P1
0 3 7
P1 P3 P2 P4
0 3 7 8 12 16
• P3 gets the CPU first since it is the shortest. P2 then P4 get the CPU in turn
(based on arrival time)
What ?
• Ready queue is treated as Circular Queue
• The CPU scheduler picks the first process from the ready
queue, sets a timer to interrupt after 1 time quantum and
dispatches the process.
Round Robin (RR)
How?(contd.)
• Two scenarios:
– The process may have CPU burst < 1 TQ ,
• the process will itself release the CPU
voluntarily
– CPU burst>1 TQ,
• the timer will go off,
• causing an interrupt to the OS,
• Context switch will be done, process will be
put at the tail of the ready queue.
Example of RR with Time Quantum = 4
Process Burst Time
P1 24
P2 3
P3 3
• The Gantt chart is:
The ATT can be improved if most processes finish their next CPU burst in single TQ
Thumb Rule- “80% of CPU bursts should be shorter than Tq”
Pre-emptive Algorithms
Shortest Remaining Time First (SRTF)
• In the Shortest Remaining Time First (SRTF) scheduling
algorithm,
– The process with the smallest amount of time remaining until
completion is selected to execute.
P1 waiting time: 0 + 4-2 = 2
P2 waiting time: 0
The average waiting time(AWT): (0 + 2) / 2 = 1
Example for Preemptive SJF (SRTF)
2 4 5
Example for Preemptive SJF (SRTF)
Process Arrival Time Burst Time
P1 0.0 7
P2 2.0 4
P3 4.0 1
P4 5.0 4
5 7 11 16
Example for Preemptive SJF (SRTF)
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
2 4 5 7 11 16
• Waiting Time for Processes:
• P1=(0+(11-2))=9, P2=((2-2)+(5-4))=1, P3=(4-4)=0, P4=(7-
5)=2
• Average waiting time = (9 + 1 + 0 +2)/4 = 3
Example of Shortest-remaining-time-first
• Now we add the concepts of varying arrival times and preemption to
the analysis
ProcessA arri Arrival TimeT Burst Time
P1 0 8
P2 1 4
P3 2 9
P4 3 5
????
Try solving this…………
Example of Shortest-remaining-time-first
ProcessA arri Arrival TimeT Burst Time
P1 0 8
P2 1 4
P3 2 9
P4 3 5
• Time 0 – P1 gets the CPU Ready = [(P1,8)]
• Time 1 – P2 arrives – CPU has P1 with rem. time=7, Ready = [(P2,4)] – P2 gets
the CPU
• Time 2 – P3 arrives – CPU has P2 with rem. time = 3, Ready = [(P1,7)(P3,9)]
– P2 continues with the CPU
• Time 3- P4 arrives- CPU has P2 with rem. time=2, Ready =[(P1,7)(P3,9)(P4,5)]
– P2 continues with the CPU
• After P2 finishes, then P4 executes , then P1 , finally P3
• Preemptive SJF Gantt Chart
Exponential averaging:
• nth CPU burst = tn
• the average of all past bursts tn,
• using a weighting factor 0<=a<=1,
• the next CPU burst is: tn+1 = a tn + (1- a) tn.
Estimating the Length of Next CPU Burst
• This formula defines an Exponential average of the measured
lengths of previous CPU bursts.
• tn= nth CPU burst , contains most recent information,
• tn =the average of all past bursts, contains past history,
• a controls the relative weight of recent and past history in our
prediction.
• We expect that the next CPU burst will be similar in length to
the previous ones.
• tn+1 = a tn + (1- a) tn.
Examples of Exponential Averaging
• a =0
– tn+1 = tn
– Recent history does not matter
• a =1
– tn+1 = a tn
– Only the most recent CPU burst matters
– history is assumed to be old and irrevelant.
tn+1 = a tn + (1- a) tn
Estimating the Length of Next CPU Burst
• More commonly a=1/2, so recent history and past history is
equally weighted
• The initial t0 can be defined as a constant or as an overall
system average
• Internally defined-
– Use Some measurable quantities
– Eg- time limits, memory requirements, the number of open
files, ratio of average I/O burst to average CPU burst have
been used
• Externally defines-
– Set by criteria that are external to the OS
– Importance of the process
– Type and amount of fund being paid for computer use
– The Department sponsoring the work
– Often political factors
Priority Scheduling
• Priority can be :
• pre-emptive
• non pre-emptive
Characteristics:
• A preemptive priority scheduling algorithm will
• preempt the CPU
• Solution Aging
Priority Scheduling
• Problem Starvation/Indefinite blocking
2 5
At time=1, P2 arrives.
P1 terminates
No other process is available at this time hence the Operating system has to
schedule P2 regardless of the priority assigned to it.
Ready Queue={(P2,BT=7,PR=6)}
Preemptive Priority Scheduling
Process Priorit Arrival Burst
Id y Time Time At Time=2
1 2 0 1 √ P3 arrives , the priority of P3 is higher to P2.
Ready Queue={(P3,BT=3,PR=3)}
2 6 1 7
6 10 5 15
7 9 15 8
Preemptive Priority Scheduling
Process Arrival Burst
Priority
Id Time Time
1 2 0 1 √
2 6 1 7
3 3 2 3
√
4 5 3 6
5 4 4 5
6 10 5 15
7 9 15 8
During the execution of P3, three more processes P4, P5 and P6 becomes
available.
Ready Queue={(P2,Rem BT=6,PR=6), (P4, BT=6,PR=5), (P5,BT=5,PR=4),
(P6,BT=15,PR=10)}
Since, all these three have the priority lower to P3,
No pre-emption, P3 continues
P3 terminates
P5 will be scheduled with the priority highest among the available processes.
Preemptive Priority Scheduling
Process Arrival Burst During the execution of P5, all the processes got
Priority available in the ready queue. At this point, the
Id Time Time
algorithm will start behaving as Non Preemptive
1 2 0 1 √ Priority Scheduling.
2 6 1 7
Ready Queue={(P2,Rem BT=6,PR=6), (P4, BT=6,PR=5),
(P6,BT=15,PR=10)}
3 3 2 3 √
4 5 3 6 √ P5 terminates
5 4 4 5 √ P4 selected with least priority in ready queue and will
6 10 5 15 be executed till the completion.
Ready Queue={(P2,Rem BT=6,PR=6),
7 9 15 8 (P6,BT=15,PR=10)}
P4 terminates
Preemptive Priority Scheduling
Ready Queue={(P2,Rem BT=6,PR=6),
Process Arrival Burst (P6,BT=15,PR=10)}
Priority
Id Time Time
P2 is selected, as it has highest priority
1 2 0 1 √ At time=15, P7 arrives
Ready Queue={(P6,BT=15,PR=10),(P7,BT=8,PR=9}
2 6 1 7 √ No pre-emption, PR of P7<PR of P2
3 3 2 3 √ P2 continues
P2 terminates
4 5 3 6
√
5 4 4 5 √
6 10 5 15
7 9 15 8
Preemptive Priority Scheduling
Process Arrival Burst
Id
Priority
Time Time
Ready Queue={(P6,BT=15,PR=10),(P7,BT=8,PR=9}
1 2 0 1 √ P7 will be selected
2 6 1 7 √
3 3 2 3 √
4 5 3 6 √
5 4 4 5 √
6 10 5 15 √
7 9 15 8 √
The only remaining process is P6 with the least priority, will be executed at the last.
Preemptive Priority Scheduling
Completion Turn around
Process Id Priority Arrival Time Burst Time Waiting Time
Time Time
1 2 0 1 1 1 0
2 6 1 7 22 21 14
3 3 2 3 5 3 0
4 5 3 6 16 13 7
5 4 4 5 10 6 1
6 10 5 15 45 40 25
7 9 6 8 30 24 16
https://www.javatpoint.com/os-preemptive-priority-scheduling
Multilevel Queue
What?
• Processes are classified into different groups.
• Common division is
– foreground (interactive)
– background (batch)
Why?
• These Processes
– have different response time requirements ,
– so have different scheduling needs.
– Foreground process have higher priority over background
processes
Multilevel Queue
How?
• Multi Level Queue Scheduling Algorithm(MQSA)
partitions Ready queue into separate queues, eg:
• If an interacting editing
process entered the ready
queue while a batch
process was running,
– the batch process would be
prempted.
Multilevel Queue
• Advantage-
– Low scheduling overhead
• Disadvantage –
– Being Inflexible
Multilevel Feedback Queue
Starvation=
• A process that waits too long in a lower priority
queue
Solution=
• Aging can be implemented this way to prevent
starvation
– may be moved to a higher priority queue.
Multilevel Feedback Queue
real-time
value
nice value
Linux Scheduling Through Version 2.5
• These two ranges map into a global priority scheme wherein
– numerically lower values indicate higher priorities.
real-time
value
nice value
Linux Scheduling Through Version 2.5
• When all tasks have exhausted their time slices (that is, the
active array is empty),
– the two priority arrays are exchanged;
– the expired array becomes the active array, and vice
versa.
Linux Scheduling (Cont.)
• Real-time scheduling according to POSIX.1b
– Real-time tasks are assigned static priorities
• Other tasks have
– dynamic priorities that are based on their nice values
plus or minus the value 5.
– The interactivity of a task determines whether
• the value 5 will be added to or subtracted from the
nice value. nice values
Linux Scheduling (Cont.)
• A task's interactivity is determined by
– how long it has been sleeping while waiting for I/0.
– Tasks that are more interactive typically have longer
sleep times and therefore are more likely to have
adjustments closer to -5,
– As the scheduler favors interactive tasks, The result of
such adjustments will be higher priorities for these tasks.
– Conversely, tasks with shorter sleep times are often
more CPU-bound and thus will have their priorities
lowered.
Linux Scheduling (Cont.)
• Tasks that are more interactive typically have longer
sleep times and therefore are more likely to have
adjustments closer to -5,
• Interactive Processes :
– These interact constantly with their users, and
therefore spend a lot of time waiting for keypresses
and mouse operations.
– When input is received, the process must be woken up
quickly, or the user will find the system to be
unresponsive.
– Typically, the average delay must fall between 50 and
150 ms.
– The variance of such delay must also be bounded, or the
user will find the system to be erratic.
– Typical interactive programs are command shells, text
editors, and graphical applications.
Linux Scheduling in Version 2.6.23 +
Completely Fair Scheduler (CFS)
– So this way each process gets fair time for the execution as
• after every context switch the virtual time of a process
increases and
• thus priority shuffles.
CFS Performance
Thread Scheduling
Thread Scheduling
• Distinction between user-level and kernel-level threads
• 2nd parameter :
– The new value for the contention scope attribute
– either PTHREAD_SCOPE_SYSTEM or PTHREAD_SCOPE_PROCESS
– indicating how the contention scope is to be set.
Description:
– Sets the thread contention scope attribute in the thread attribute
object attr to scope.
http://www.qnx.com/developers/docs/qnxcar2/index.jsp?topic=%2Fcom.qnx.doc.neutrino.lib_ref%2Ftopic%2Fp%2Fpthread_attr_setscope.html
Pthread Scheduling
pthread_attr_getscope(pthread_attr_t *attr, int *scope)
• 2nd parameter :
– A pointer to a location where the function can store the current
contention scope.
Description:
• Gets the thread contention scope attribute from the thread attribute
object attr and returns it in scope.
http://www.qnx.com/developers/docs/qnxcar2/index.jsp?topic=%2Fcom.qnx.doc.neutrino.lib_ref%2Ftopic%2Fp%2Fpthread_attr_setscope.html
Pthread Scheduling API
• The program first determines the existing contention scope and sets
it to PTHREAD_SCOPE_SYSTEM.
• It then creates five separate threads that will run using the SCS
scheduling policy.
#include <pthread.h>
#include <stdio.h>
#define NUM_THREADS 5
int main(int argc, char *argv[]) {
int i, scope;
pthread_t tid[NUM THREADS];
pthread_attr_t attr;
/* get the default attributes */
pthread_attr_init(&attr);
/* first inquire on the current scope */
if (pthread_attr_getscope(&attr, &scope) != 0)
fprintf(stderr, "Unable to get scheduling scope\n");
else {
if (scope == PTHREAD_SCOPE_PROCESS)
printf("PTHREAD_SCOPE_PROCESS");
else if (scope == PTHREAD_SCOPE_SYSTEM)
printf("PTHREAD_SCOPE_SYSTEM");
else
fprintf(stderr, "Illegal scope value.\n");
}
Pthread Scheduling
pthread_attr_init()
• Initialize a thread-attribute object
Synopsis:
#include <pthread.h>
int pthread_attr_init( pthread_attr_t *attr );
Arguments:
• attr -A pointer to the pthread_attr_t structure that you want
to initialize.
http://www.qnx.com/developers/docs/qnxcar2/index.jsp?topic=%2Fcom.qnx.doc.neutrino.lib_ref%2Ftopic%2Fp%2Fpthread_attr_setscope.html
Pthread Scheduling API
/* set the scheduling algorithm to PCS or SCS */
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
/* create the threads */
for (i = 0; i < NUM_THREADS; i++)
pthread_create(&tid[i],&attr,runner,NULL);
/* now join on each thread */
for (i = 0; i < NUM_THREADS; i++)
pthread_join(tid[i], NULL);
}
/* Each thread will begin control in this function */
void *runner(void *param)
{
/* do some work ... */
pthread_exit(0);
}
Pthread Scheduling
pthread_create()
• Create a thread
Synopsis:
#include <pthread.h>
int pthread_create( pthread_t* thread, const pthread_attr_t*
attr, void* (*start_routine)(void* ), void* arg );
http://www.qnx.com/developers/docs/qnxcar2/index.jsp?topic=%2Fcom.qnx.doc.neutrino.lib_ref%2Ftopic%2Fp%2Fpthread_attr_setscope.html
Pthread Scheduling
int pthread_create( pthread_t* thread, const pthread_attr_t*
attr, void* (*start_routine)(void* ), void* arg );
Arguments:
• thread –
– NULL, or a pointer to a pthread_t object where the
function can store the thread ID of the new thread.
• attr -
– A pointer to a pthread_attr_t structure that specifies the
attributes of the new thread.
– Instead of manipulating the members of this structure
directly, use pthread_attr_init() and the
pthread_attr_set_* functions.
– If you modify the attributes in attr after creating the
thread, the thread's attributes aren't affected.
Pthread Scheduling
int pthread_create( pthread_t* thread, const pthread_attr_t*
attr, void* (*start_routine)(void* ), void* arg );
Arguments:
• start_routine-
– The routine where the thread begins, with arg as its only argument. If
start_routine() returns,
– There's an implicit call to pthread_exit(), using the return value of
start_routine() as the exit status.
– The thread in which main() was invoked behaves differently. When it
returns from main(), there's an implicit call to exit(), using the return
value of main() as the exit status.
• arg The argument to pass to start_routine.
http://www.qnx.com/developers/docs/qnxcar2/index.jsp?topic=%2Fcom.qnx.doc.neutrino.lib_ref%2Ftopic%2Fp%2Fpthread_attr_setscope.html
Pthread Scheduling
• int pthread_create( pthread_t* thread, const pthread_attr_t*
attr, void* (*start_routine)(void* ), void* arg );
• pthread_create(&tid[i],&attr,runner,NULL);
http://www.qnx.com/developers/docs/qnxcar2/index.jsp?topic=%2Fcom.qnx.doc.neutrino.lib_ref%2Ftopic%2Fp%2Fpthread_attr_setscope.html
Pthread Scheduling
Joining
• The simplest method of synchronization is to join the threads
as they terminate.
• value_ptr –
– An optional value_ptr, which can be used to store the termination
return value from the joined thread.
– NULL, or a pointer to a location where the function can store the value
passed to pthread_exit() by the target thread.
– You can pass in a NULL if you aren't interested in this value
Pthread Scheduling
• The pthread_join function returns an integer value that also
indicates different error codes.
Return Value-
• 0 if the call was successful and this guarantees the given
thread has terminated.
• EDEADLK- a deadlock was detected.
• EINVAL- the given thread is not joinable
• ESRCH- the given thread ID can’t be found.
Pthread Scheduling API
/* set the scheduling algorithm to PCS or SCS */
pthread_attr_setscope(&attr, PTHREAD_SCOPE_SYSTEM);
/* create the threads */
for (i = 0; i < NUM_THREADS; i++)
pthread_create(&tid[i],&attr,runner,NULL);
/* now join on each thread */
for (i = 0; i < NUM_THREADS; i++)
pthread_join(tid[i], NULL);
}
/* Each thread will begin control in this function */
void *runner(void *param)
{
/* do some work ... */
pthread_exit(0);
}
The calling thread waits for every thread with the
pthread_join call in the loop
Pthread Scheduling API
#include <pthread.h>
/* set the scheduling algorithm to PCS
#include <stdio.h> or SCS */
#define NUM_THREADS 5 pthread_attr_setscope(&attr,
int main(int argc, char *argv[]) { PTHREAD_SCOPE_SYSTEM);
int i, scope; /* create the threads */
pthread_t tid[NUM THREADS]; for (i = 0; i < NUM_THREADS; i++)
pthread_attr_t attr; pthread_create(&tid[i],&attr,runner,NUL
/* get the default attributes */ L);
pthread_attr_init(&attr); /* now join on each thread */
/* first inquire on the current scope */ for (i = 0; i < NUM_THREADS; i++)
if (pthread_attr_getscope(&attr, &scope) pthread_join(tid[i], NULL);
!= 0) }
fprintf(stderr, "Unable to get /* Each thread will begin control in
this function */
scheduling scope\n");
void *runner(void *param)
else { {
if (scope == PTHREAD_SCOPE_PROCESS) /* do some work ... */
printf("PTHREAD_SCOPE_PROCESS"); pthread_exit(0);
else if (scope == }
PTHREAD_SCOPE_SYSTEM)
printf("PTHREAD_SCOPE_SYSTEM");
else
fprintf(stderr, "Illegal scope
value.\n");
}
Pthread Scheduling
pthread_exit()
• Terminate a thread
Synopsis:
#include <pthread.h>
void pthread_exit( void* value_ptr );
Arguments:
• value_ptr A pointer to a value that you want to be made available to any
thread joining the thread that you're terminating.
Description:
• Terminates the calling thread.
• This routine kills the thread
• If the thread is joinable, the value value_ptr is made available to any
thread joining the terminating thread (only one thread can get the return
status).
• If the thread is detached, all system resources allocated to the thread are
immediately reclaimed.