Home
5CPU Scheduling
5

Chapter 5 · Final syllabus · Lectures 15–18

CPU Scheduling

CPU–I/O bursts, preemptive and nonpreemptive scheduling, scheduling criteria, FCFS, SJF, SRTF, round robin, priority, priority with RR, multilevel and multilevel feedback queues, and evaluation by deterministic modelling, Little’s formula and simulation.

← → move between slides · F full screen · M slide list

Before we start

Why this matters

Ten processes are ready and there is one core. Who runs next, and for how long?

The answer decides whether your music stutters, whether a long job ever finishes, and how long everyone waits.

This chapter compares the classic scheduling algorithms on the same workloads, with Gantt charts you can rebuild and change.

Chapter 5 · Lectures 15–18

Outline

Select a topic to jump to the slide that explains it.

  1. Basic concepts
  2. Scheduling criteria
  3. Scheduling algorithms
  4. Algorithm evaluation

Basic concepts

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 followed by I/O burst
  • CPU burst distribution is of main concern

Basic concepts

Basic concepts (cont.)

Alternating sequence of CPU and I/O bursts.

Basic concepts

Histogram of CPU-burst times

  • Large number of short bursts
  • Small number of longer bursts
An I/O-bound program has many short CPU bursts; a CPU-bound program has a few long ones. The scheduler should favour the short ones.

Basic concepts

Histogram of CPU-burst times (cont.)

Histogram of CPU-burst durations.

Basic concepts

CPU scheduler

  • The CPU scheduler selects from among the processes in ready queue, and allocates a CPU core to one of them
    • Queue may be ordered in various ways
  • 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
  • For situations 1 and 4, there is no choice in terms of scheduling. A new process (if one exists in the ready queue) must be selected for execution.
  • For situations 2 and 3, however, there is a choice.

Basic concepts

Preemptive and nonpreemptive scheduling

  • When scheduling takes place only under circumstances 1 and 4, the scheduling scheme is nonpreemptive.
  • Otherwise, it is preemptive.
  • Under nonpreemptive scheduling, once the CPU has been allocated to a process, the process keeps the CPU until it releases it either by terminating or by switching to the waiting state.
  • Virtually all modern operating systems including Windows, MacOS, Linux, and UNIX use preemptive scheduling algorithms.

Basic concepts

Preemptive scheduling and race conditions

  • Preemptive scheduling can result in race conditions when data are shared among several processes.
  • Consider the case of two processes that share data. While one process is updating the data, it is preempted so that the second process can run. The second process then tries to read the data, which are in an inconsistent state.
  • This issue will be explored in detail in Chapter 6.

Scheduling criteria

Scheduling criteria

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

Optimization criteria

  • Max CPU utilization
  • Max throughput
  • Min turnaround time
  • Min waiting time
  • Min response time
turnaround = completion − arrival  ·  waiting = turnaround − burst  ·  response = first run − arrival

FCFS

First-come, first-served (FCFS) scheduling

ProcessBurst time
P124
P23
P33

Suppose that the processes arrive in the order: P1, P2, P3. The Gantt chart for the schedule is:

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

FCFS

FCFS scheduling (cont.)

Suppose that the processes arrive in the order: P2, P3, P1. The Gantt chart for the schedule is:

  • 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
    • Consider one CPU-bound and many I/O-bound processes

Code and output

FCFS in C

fcfs.c
#include <stdio.h>

int main(void)
{
    char *name[] = {"P1", "P2", "P3"};
    int burst[]  = {24, 3, 3};          /* all arrive at time 0, in this order */
    int n = 3, t = 0, total = 0;

    printf("Process  Burst  Waiting  Turnaround\n");
    for (int i = 0; i < n; i++) {
        int wait = t;                   /* FCFS: waits for everyone before it */
        t += burst[i];

Code and output

FCFS in C (cont.)

        total += wait;
        printf("%-7s  %5d  %7d  %10d\n", name[i], burst[i], wait, t);
    }
    printf("Average waiting time = %.2f\n", (double)total / n);
    return 0;
}
Output
Terminal
$ gcc fcfs.c -o fcfs -pthread && ./fcfs
Process  Burst  Waiting  Turnaround
P1          24        0          24
P2           3       24          27
P3           3       27          30
Average waiting time = 17.00

Each process waits for the bursts of everyone before it: the same 0, 24, 27 and average 17 as the Gantt chart.

SJF

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
  • SJF is optimal – gives minimum average waiting time for a given set of processes
  • Preemptive version called shortest-remaining-time-first
  • How do we determine the length of the next CPU burst?
    • Could ask the user
    • Estimate

SJF

Example of SJF

ProcessBurst time
P16
P28
P37
P43

SJF scheduling chart:

Average waiting time = (3 + 16 + 9 + 0) / 4 = 7

SJF

Example of SJF (cont.)

This chart assumes all four processes are in the ready queue at time 0. The original slide’s table also lists arrival times 0, 2, 4 and 5; with those arrivals P1 must start alone and the average is 5. Try both in the simulator at the end of the chapter.

SRTF

Example of shortest-remaining-time-first

Now we add the concepts of varying arrival times and preemption to the analysis.

ProcessArrival timeBurst time
P108
P214
P329
P435

Preemptive SJF Gantt chart:

Average waiting time = [(10 − 1) + (1 − 1) + (17 − 2) + (5 − 3)] / 4 = 26 / 4 = 6.5

Round robin

Round robin (RR)

  • Each process gets a small unit of CPU time (time quantum q), 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.
  • Timer interrupts every quantum to schedule next process
  • Performance
    • q large → FIFO
    • q small → q must be large with respect to context switch, otherwise overhead is too high

Round robin

Example of RR with time quantum = 4

ProcessBurst time
P124
P23
P33
  • Typically, higher average turnaround than SJF, but better response
  • q should be large compared to context switch time
    • q usually 10 milliseconds to 100 milliseconds
    • Context switch < 10 microseconds

Round robin

Example of RR with time quantum = 4 (cont.)

The Gantt chart is:

Round robin

Time quantum and context switch time

How a smaller time quantum increases context switches.

Priority

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 priority scheduling where priority is the inverse of predicted next CPU burst time
  • Problem → starvation – low priority processes may never execute
  • Solution → aging – as time progresses increase the priority of the process

Priority

Example of priority scheduling

ProcessBurst timePriority
P1103
P211
P324
P415
P552

Priority scheduling Gantt chart:

Average waiting time = (6 + 0 + 16 + 18 + 1) / 5 = 8.2

Priority

Priority scheduling with round-robin

ProcessBurst timePriority
P143
P252
P382
P471
P533
  • Run the process with the highest priority. Processes with the same priority run round-robin

Gantt chart with time quantum = 2:

Animated

Watch the scheduler run

Multilevel queue

Multilevel queue

  • With priority scheduling, have separate queues for each priority.
  • Schedule the process in the highest-priority queue!

Multilevel queue

Multilevel queue (cont.)

Separate queues for each priority.

Multilevel queue

Multilevel queue (cont.)

Prioritization based upon process type:

Multilevel queue

Multilevel queue (cont.)

Multilevel queue scheduling.

Multilevel feedback queue

Multilevel feedback queue

  • A process can move between the various queues.
  • 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
  • Aging can be implemented using multilevel feedback queue

Multilevel feedback queue

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 process enters queue Q0 which is served in RR
      • When it gains CPU, the process receives 8 milliseconds
      • If it does not finish in 8 milliseconds, the process is moved to queue Q1
    • At Q1 job is again served in RR and receives 16 additional milliseconds
      • If it still does not complete, it is preempted and moved to queue Q2

Multilevel feedback queue

Example of multilevel feedback queue (cont.)

Multilevel feedback queues.

Interactive

Run the multilevel feedback queue

Algorithm evaluation

Algorithm evaluation

  • How to select CPU-scheduling algorithm for an OS?
  • Determine criteria, then evaluate algorithms
  • Deterministic modeling
    • Type of analytic evaluation
    • Takes a particular predetermined workload and defines the performance of each algorithm for that workload
  • Consider 5 processes arriving at time 0:
ProcessBurst time
P110
P229
P33
P47
P512

Algorithm evaluation

Deterministic evaluation

  • For each algorithm, calculate minimum average waiting time
  • Simple and fast, but requires exact numbers for input, applies only to those inputs
  • FCFS is 28 ms, non-preemptive SJF is 13 ms, RR (q = 10) is 23 ms:

Algorithm evaluation

Deterministic evaluation (cont.)

Algorithm evaluation

Queueing models and Little’s formula

  • Describes the arrival of processes, and CPU and I/O bursts probabilistically
    • Commonly exponential, and described by mean
    • Computes average throughput, utilization, waiting time, etc.
  • Computer system described as network of servers, each with queue of waiting processes
    • Knowing arrival rates and service rates
    • Computes utilization, average queue length, average wait time, etc.
  • n = average queue length; W = average waiting time in queue; λ = average arrival rate into queue
  • Little’s law – in steady state, processes leaving queue must equal processes arriving, thus: n = λ × W
    • Valid for any scheduling algorithm and arrival distribution

Algorithm evaluation

Queueing models and Little’s formula (cont.)

  • For example, if on average 7 processes arrive per second, and normally 14 processes in queue, then average wait time per process = 2 seconds

Algorithm evaluation

Simulations

  • Queueing models limited
  • Simulations more accurate
    • Programmed model of computer system
    • Clock is a variable
    • Gather statistics indicating algorithm performance
    • Data to drive simulation gathered via
      • Random number generator according to probabilities
      • Distributions defined mathematically or empirically
      • Trace tapes record sequences of real events in real systems

Algorithm evaluation

Simulations (cont.)

Evaluation of CPU schedulers by simulation.

Algorithm evaluation

Implementation

  • Even simulations have limited accuracy
  • Just implement new scheduler and test in real systems
    • High cost, high risk
    • Environments vary
  • Most flexible schedulers can be modified per-site or per-system
  • Or APIs to modify priorities
  • But again environments vary

Interactive · every algorithm

CPU-scheduling simulator

Worked example 1 of 2

Worked example 1

Processes P1 (arrival 0, burst 5), P2 (1, 3), P3 (2, 1), P4 (3, 2). Draw the Gantt chart and find the average waiting time for SJF (non-preemptive) and SRTF.
Show the solution

SJF: P1 0–5 (only P1 has arrived), then shortest first: P3 5–6, P4 6–8, P2 8–11. Waiting: P1 0, P2 7, P3 3, P4 3 → average 3.25.

SRTF: P1 0–1, P2 1–2, P3 2–3, P2 3–5, P4 5–7, P1 7–11. Waiting: P1 6, P2 1, P3 0, P4 2 → average 2.25.

Worked example 2 of 2

Worked example 2

Same four processes, Round Robin with q = 2. Find the average waiting and response times.
Show the solution

Arrivals that come during a quantum join the queue before the preempted process. Compare with SJF: RR has worse waiting time but every process starts quickly.

Practice

Practice (1 of 2)

Try each one on paper first, then check your answer.

1. What are the four situations in which a CPU-scheduling decision may happen, and which make scheduling preemptive?
Show the answer
Running → waiting, running → ready, waiting → ready, terminates. Scheduling only on 1 and 4 is nonpreemptive; deciding also on 2 or 3 makes it preemptive.
2. Define turnaround, waiting and response time.
Show the answer
Turnaround: from submission to completion. Waiting: total time spent in the ready queue. Response: from submission until the first response is produced.
3. What is the convoy effect?
Show the answer
With FCFS, short processes wait behind one long process, like cars behind a slow truck; e.g. many I/O-bound processes behind one CPU-bound process.

Practice

Practice (2 of 2)

Try each one on paper first, then check your answer.

4. Why is SJF hard to implement, and how is it approximated?
Show the answer
The length of the next CPU burst is not known. It can be asked from the user or estimated (usually from the lengths of previous bursts).
5. How does aging solve starvation?
Show the answer
The priority of a waiting process is gradually increased with time, so even a low-priority process eventually becomes the highest priority and runs.
6. If 5 processes arrive per second on average and each waits 3 seconds, how many are in the queue on average?
Show the answer
Little’s law: n = λ × W = 5 × 3 = 15 processes.

Check yourself

Quiz

Summary · End of Chapter 5

Summary

  • Processes alternate CPU and I/O bursts; most bursts are short.
  • The scheduler picks from the ready queue; it is preemptive if it can take the CPU away, which can cause race conditions.
  • Criteria: maximize CPU utilization and throughput; minimize turnaround, waiting and response time.
  • FCFS is simple but suffers the convoy effect; SJF is optimal for waiting time; SRTF is its preemptive form.
  • RR shares the CPU in quanta (q large → FCFS, q small → many context switches); priority scheduling risks starvation, cured by aging.
  • Multilevel (feedback) queues combine algorithms; algorithms are evaluated by deterministic modelling, queueing models (n = λW), simulation and implementation.