CPU Scheduling and Deadlock

UNIT 2 • MODULE 3 • LESSON 04

Imagine one cashier and a line of shoppers. One has a full trolley, the next has a single loaf of bread, the next has three items. Who should be served first? Serving in arrival order feels fair, but the person with the loaf may wait twenty minutes for a ten-second sale. Letting short jobs go first gets most people out quickly, but the full trolley might never reach the till on a busy day. An operating system faces exactly this choice thousands of times a second, and the rule it uses is called a scheduling algorithm.

In this lesson you will trace the four scheduling algorithms named in the syllabus, measure them with waiting and turnaround times, and run them in C. Then you will meet the opposite problem: processes that wait forever because each holds something the other needs. That is deadlock, and you will see how an OS prevents it or breaks it.

What you will learn

  • What the scheduler does and how it uses the ready queue.
  • The difference between pre-emptive and non-pre-emptive scheduling.
  • First-come-first-served, shortest-job-first (both versions) and round robin.
  • How to draw a Gantt chart and calculate waiting and turnaround times.
  • A C program that applies the algorithms to a job list.
  • What deadlock is, the four conditions that cause it, and how it can be prevented or resolved.

Part 1: The scheduler and the ready queue

Lesson 03 showed that processes able to run wait in the ready queue. The scheduler is the part of the OS that picks which ready process gets the processor next; the dispatcher then performs the context switch. The ready queue is a queue in the sense of Unit 2 • Module 1 • Lesson 04 – Queues: FIFO, Enqueue, Dequeue and Linear Queues in C, although some algorithms choose from it in an order other than first-in, first-out.

A good scheduling algorithm tries to balance several goals: keep the CPU busy, finish many jobs per hour (throughput), keep each process’s total time in the system low (turnaround), keep time spent waiting low, respond quickly to interactive users, and be fair so that no process waits for ever.

Pre-emptive and non-pre-emptive

Non-pre-emptivePre-emptive
RuleOnce a process has the CPU it keeps it until it finishes or blocksThe OS may take the CPU away from a running process
Triggered byThe running process finishing or waiting for I/OA timer interrupt, or a more urgent process becoming ready
Good forSimple systems, batch workInteractive and time-sharing systems
ExamplesFCFS; SJF (non-pre-emptive)Round robin; SJF (pre-emptive), also called shortest remaining time first

Part 2: Measuring an algorithm

Each process (we will call them jobs) has an arrival time and a burst time, the amount of CPU time it needs. From a schedule we work out:

turnaround = finish - arrival
waiting    = turnaround - burst
average    = total / number of jobs

A Gantt chart is a timeline showing which job holds the CPU in each time unit. It is the easiest way to work out finish times. We will use this job set throughout:

JobArrivalBurst
P106
P213
P321
P434

Part 3: The four algorithms

First-come, first-served (FCFS), non-pre-emptive

Run jobs in order of arrival, each to completion. Simple and fair in one sense, but a long job at the front makes every short job behind it wait (the convoy effect).

| P1 0-6 | P2 6-9 | P3 9-10 |
| P4 10-14 |
Waits: P1 0, P2 5, P3 7, P4 7
Average wait = 19 / 4 = 4.75

Shortest job first (SJF), non-pre-emptive

Whenever the CPU becomes free, choose the ready job with the smallest burst. A job that is running is not interrupted. At time 0 only P1 has arrived, so it runs to 6. Then P3 (1) is shortest, then P2 (3), then P4 (4).

| P1 0-6 | P3 6-7 | P2 7-10 |
| P4 10-14 |
Waits: P1 0, P2 6, P3 4, P4 7
Average wait = 17 / 4 = 4.25

Shortest job first, pre-emptive (shortest remaining time first)

Every time a job arrives, compare its burst with the remaining time of the running job. If the newcomer is shorter, pre-empt. P1 starts; at time 1, P2 (3) is shorter than P1’s remaining 5, so P2 takes over; at 2, P3 (1) is shorter than P2’s remaining 2; and so on.

| P1 0-1 | P2 1-2 | P3 2-3 |
| P2 3-5 | P4 5-9 | P1 9-14 |
Waits: P1 8, P2 1, P3 0, P4 2
Average wait = 11 / 4 = 2.75

This gives the lowest possible average waiting time. Its weaknesses: the OS cannot really know burst times in advance (it estimates them from past behaviour), and a long job may wait for ever if short jobs keep arriving. That is called starvation. A common fix is ageing: gradually raise the priority of jobs that have waited a long time.

Round robin (RR), pre-emptive

Each job in turn gets a fixed time quantum (time slice), here 2 units. If it has not finished, a timer interrupt pre-empts it and it goes to the back of the ready queue. Jobs that arrive during a slice join the queue before the job that was just pre-empted.

| P1 0-2 | P2 2-4 | P3 4-5 |
| P1 5-7 | P4 7-9 | P2 9-10 |
| P1 10-12 | P4 12-14 |
Waits: P1 6, P2 6, P3 2, P4 7
Average wait = 21 / 4 = 5.25

Round robin’s average wait is not the best here, but no job waits long for its first turn, so it suits interactive systems where every user expects a quick response. The quantum matters: too large and RR behaves like FCFS; too small and the CPU spends much of its time context switching.

AlgorithmPre-emptive?StrengthWeakness
FCFSNoSimple; no starvationShort jobs stuck behind long ones
SJFNoLow average waitNeeds burst estimates; long jobs can starve
SJF (pre-emptive)YesLowest average waitMore switches; starvation possible
Round robinYesFair, good response timeMany switches; result depends on quantum

Now run the algorithms yourself. Change the job set and see whether the same algorithm always wins.

Try it 1Scheduling race: Gantt chart builder

Choose a job set and an algorithm. Each box is one time unit; the number under it is the time it starts.

For the selected set, which algorithm gives the lowest average waiting time?

Part 4: Scheduling in C

The program below stores the job set in two parallel arrays and applies FCFS, non-pre-emptive SJF and round robin. Read the pseudocode for round robin first, then find each line in the C.

t <- 0
WHILE jobs are left
  add jobs that have arrived
    to the BACK of the queue
  IF queue empty THEN t <- t + 1
  ELSE
    p <- take FRONT of queue
    run p for min(quantum,
                  remaining)
    add new arrivals to queue
    IF p not finished THEN
      put p at the BACK
    ELSE record finish time
ENDWHILE
#include <stdio.h>

#define N 4

int arr[N] = {0, 1, 2, 3};
int burst[N] = {6, 3, 1, 4};

void report(const char *name, int fin[])
{
    int i, tw = 0;
    printf("%s\n", name);
    for (i = 0; i < N; i++) {
        int ta = fin[i] - arr[i];
        int w = ta - burst[i];
        tw += w;
        printf("  P%d finish %2d wait %d\n",
               i + 1, fin[i], w);
    }
    printf("  average wait %.2f\n",
           tw / (double) N);
}

/* First come, first served */
void fcfs(void)
{
    int fin[N], t = 0, i;
    for (i = 0; i < N; i++) {
        if (t < arr[i]) t = arr[i];
        t += burst[i];
        fin[i] = t;
    }
    report("FCFS", fin);
}

/* Shortest job first, non-pre-emptive */
void sjf(void)
{
    int fin[N], done[N] = {0};
    int t = 0, count, i;
    for (count = 0; count < N; count++) {
        int best = -1;
        for (i = 0; i < N; i++) {
            if (done[i] || arr[i] > t)
                continue;
            if (best == -1 ||
                burst[i] < burst[best])
                best = i;
        }
        if (best == -1) { t++; count--;
                          continue; }
        t += burst[best];
        fin[best] = t;
        done[best] = 1;
    }
    report("SJF (non-pre-emptive)", fin);
}

/* Round robin with a time quantum */
void rr(int q)
{
    int rem[N], fin[N], queue[64];
    int head = 0, tail = 0, t = 0;
    int next = 0, i, left = N;
    for (i = 0; i < N; i++)
        rem[i] = burst[i];
    while (left > 0) {
        while (next < N && arr[next] <= t)
            queue[tail++] = next++;
        if (head == tail) { t++; continue; }
        int p = queue[head++];
        int run = rem[p] < q ? rem[p] : q;
        t += run;
        rem[p] -= run;
        while (next < N && arr[next] <= t)
            queue[tail++] = next++;
        if (rem[p] > 0) queue[tail++] = p;
        else { fin[p] = t; left--; }
    }
    report("Round robin (q = 2)", fin);
}

int main(void)
{
    fcfs();
    sjf();
    rr(2);
    return 0;
}

Output:

FCFS
  P1 finish  6 wait 0
  P2 finish  9 wait 5
  P3 finish 10 wait 7
  P4 finish 14 wait 7
  average wait 4.75
SJF (non-pre-emptive)
  P1 finish  6 wait 0
  P2 finish 10 wait 6
  P3 finish  7 wait 4
  P4 finish 14 wait 7
  average wait 4.25
Round robin (q = 2)
  P1 finish 12 wait 6
  P2 finish 10 wait 6
  P3 finish  5 wait 2
  P4 finish 14 wait 7
  average wait 5.25

The output matches the hand-drawn charts above. Note how the round robin function uses an array as a simple queue with head and tail indexes, just like the linear queue from Unit 2 Module 1 (64 slots is plenty for this small job set). The SJF function scans the jobs that have arrived and are not done, choosing the smallest burst. Because a scheduler like this is one of the project ideas in the syllabus, extending this program is a realistic start for an internal assessment.

How this supports the Unit 2 internal assessment

The syllabus lists a simple process scheduler among its example projects. If you choose it, the analysis would gather what users need to see (Gantt chart, waits, averages); the design would include a structure chart with modules such as readJobs, fcfs, sjf, rr and report; and your test plan would use small job sets whose answers you have worked out by hand, exactly as in Part 3.

Part 5: Deadlock

Scheduling decides who gets the CPU. Processes also need other resources, such as printers, files and memory, that only one process can use at a time. Deadlock is a situation in which two or more processes are each waiting for a resource held by another process in the group, so none of them can ever continue.

A classic example: process A has the printer and asks for the scanner; process B has the scanner and asks for the printer. Each waits for the other. Neither will release what it holds, so both wait for ever.

The four conditions

Deadlock can only happen if all four of these are true at once:

ConditionMeaningIn the example
Mutual exclusionA resource can be used by only one process at a timeOnly one process can print at once
Hold and waitA process holds one resource while waiting for anotherA holds the printer and waits for the scanner
No pre-emptionA resource cannot be taken away; it must be releasedThe OS will not snatch the scanner from B
Circular waitA closed chain of processes, each waiting for the nextA waits for B and B waits for A

Dealing with deadlock

  • Prevention: design rules so one condition can never hold. For example, make every process request resources in a fixed order (breaks circular wait), or request everything it needs at the start (breaks hold and wait).
  • Avoidance: before granting a request, the OS checks whether granting it could lead to deadlock, and makes the process wait if so.
  • Detection and recovery: let deadlocks happen, detect the circle, then break it by aborting one or more processes, or pre-empting a resource and rolling the process back to a safe point.
  • Ignoring it: some desktop systems simply leave it to the user to close a frozen program, because deadlock is rare and prevention is costly.

Try it 2Deadlock: get things moving again

Two processes are stuck. Try each action and decide which ones resolve or prevent the deadlock. There are three working fixes.


Deadlock is not the same as starvation. In starvation a process could run but keeps being passed over (for example, a long job under SJF). In deadlock, the processes involved cannot run, whatever the scheduler does.

Part 6: Common mistakes

  • Calling SJF only non-pre-emptive. The syllabus names both versions. Say which one you mean.
  • Forgetting arrival times. A job cannot be chosen before it arrives. Always check who is in the queue at each decision point.
  • Waiting = finish time. No: waiting = turnaround minus burst, and turnaround = finish minus arrival.
  • Describing deadlock as "the computer is slow". Describe the circular wait on held resources.

Try it 3Scheduling and deadlock drill

Pick a mode. "Calc" gives a small job set and asks for a time. "Ideas" checks the key terms.

Summary

IdeaRemember
SchedulerChooses the next ready process; the dispatcher switches to it.
Non-pre-emptiveFCFS and SJF: run until finish or block.
Pre-emptiveRound robin and SJF (shortest remaining time): the OS can take the CPU back.
Formulaeturnaround = finish - arrival; waiting = turnaround - burst.
DeadlockCircular wait for held resources; needs mutual exclusion, hold and wait, no pre-emption, circular wait.
FixesPrevent (break a condition), avoid, or detect and recover (abort or pre-empt).

Review questions

1. Distinguish between pre-emptive and non-pre-emptive scheduling.

Show answer

Non-pre-emptive: a process keeps the CPU until it finishes or blocks. Pre-emptive: the OS can remove the CPU from a running process, for example when its time slice ends or a shorter job arrives.

2. Explain how the round-robin algorithm works.

Show answer

Each ready process in turn is given a fixed time quantum. If it has not finished when the quantum ends, a timer interrupt pre-empts it and it goes to the back of the ready queue; the next process is dispatched.

3. Jobs X (arrival 0, burst 4), Y (0, 1), Z (0, 2). Give the average waiting time for FCFS (order X, Y, Z) and for SJF.

Show answer

FCFS: waits 0, 4, 5, average 3. SJF: order Y, Z, X, waits Y 0, Z 1, X 3, average 4/3 ≈ 1.33.

4. Give a strength and a weakness of shortest-job-first scheduling.

Show answer

Advantage: lowest average waiting time. Disadvantage: burst times must be estimated, and long jobs can starve.

5. Define deadlock.

Show answer

A state in which two or more processes are each waiting for a resource held by another in the group, so none can proceed.

6. List the four conditions needed for deadlock.

Show answer

Mutual exclusion, hold and wait, no pre-emption, circular wait.

7. Describe two ways of resolving a deadlock once it has happened.

Show answer

Abort one or more of the processes to release their resources; or pre-empt a resource from one process, give it to another, and roll the first process back.

8. Explain how requesting resources in a fixed order prevents deadlock.

Show answer

If every process requests resources in the same order, no process can hold a later resource while waiting for an earlier one, so a circular chain of waits cannot form.

Homework

  1. For the jobs P1 (0, 5), P2 (1, 2), P3 (2, 4), P4 (4, 1), draw Gantt charts for all four algorithms (q = 2) and calculate the average waiting times. Check them with Try it 1 by editing sched.c.
  2. Change the quantum in sched.c to 1 and then to 6. Explain what happens to the average wait and to the number of switches.
  3. Add a function to sched.c for pre-emptive SJF.
  4. Describe a real-life deadlock (for example, cars at a four-way junction) and identify the four conditions in it.

Mastery quiz: CPU Scheduling and Deadlock

This 10-question quiz is separate from the short Quick quiz at the end of the lesson. Score 8/10 or higher to earn this lesson’s badge. Your best score is saved in this browser on this device.

Mastery quiz: CPU Scheduling and Deadlock

Your course badges: loading saved progress…

View badges

    No course badges earned yet. Score 8/10 in a lesson quiz to earn its badge.

    Saved in this browser on this device. Clearing browser data may remove your badges.

    Answer all 10 questions. Earn this lesson’s badge at 8/10 or higher. Read the explanations, revisit the Try it activities and retry as often as you need. These are self-study badges, not formal grades.

    1. Which algorithm is non-pre-emptive?
    2. In round robin, a process that uses up its quantum...
    3. Turnaround time is...
    4. A job arrives at 2, needs 3 units and finishes at 9. Its waiting time is...
    5. Which algorithm gives the lowest average waiting time?
    6. A long job never runs because short jobs keep arriving. This is...
    7. Which is NOT one of the four deadlock conditions?
    8. Requesting all resources in the same fixed order prevents deadlock by breaking...
    9. Which recovers from deadlock?
    10. A very large round-robin quantum makes it behave like...

    Exam tips

    Specimen Unit 2 Paper 02 (2021), Question 5(d). Explaining round robin earns marks for three points: each process gets a fixed time slice, an unfinished process goes to the back of the queue, and the next process in the queue is given the CPU. Mention the timer interrupt for an extra link to Lesson 03.

    Calculations. If a question gives arrival and burst times, draw the Gantt chart first, label the times underneath, then make a table of finish, turnaround and waiting. Show the formula once. Marks are often given for the chart even if an average is wrong.

    Deadlock questions. Define it with "each waiting for a resource held by another", then name the conditions or a resolution as asked. A labelled diagram of two processes and two resources makes the circular wait obvious.

    Past paper practice. 2019 Unit 2 Paper 02 Question 5 (scheduling) and 2018 Unit 2 Paper 02 Question 5 (deadlock) have worked answers on the CS Solutions page.

    Previous: Unit 2 • Module 3 • Lesson 03 – Processes: States, the Process Control Block and Interrupts. Next: Unit 2 • Module 3 • Lesson 05 – Memory Management: Virtual Memory, Paging and Thrashing.

    Syllabus link: CAPE Computer Science (CXC A19/U2/21), Operating Systems and Computer Networks (Unit 2, Module 3). Specific Objective 3: describe the functions of operating systems (process management: deadlock and deadlock resolution; scheduling algorithms: pre-emptive (shortest job first, round robin) and non-pre-emptive (first come first serve, shortest job first)).

    Video search terms

    Search YouTube for: "CPU scheduling FCFS SJF round robin Gantt chart", "shortest remaining time first example", "deadlock four conditions".

    Try it 4Quick quiz

    Tap an answer. All eight questions are self-checks on this lesson.

    Updates

    2026/12/01

    - First version of the lesson.

    © 2026 islandclass.org

    Leave a Reply