---
title: "The Kernel and CPU Scheduling"
book: "University Computer Science — Year 3"
subject: computer-science
language: en
chapter: 10
exercises: 12
source: https://one-course.com/books/computer-science/5/en/chapter/10-the-kernel-and-cpu-scheduling
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 10 — The Kernel and CPU Scheduling

A laptop runs many more processes than it has processor cores, and each process behaves as if it had a processor of its own. The Year 2 volume used that illusion from the outside, through system calls. This chapter builds it from the inside: how control gets into the [kernel](#def-b3-kernel-and-scheduling-kernel) and back out, how the [kernel](#def-b3-kernel-and-scheduling-kernel) stops one program and resumes another exactly where it was, and how it decides which one runs next. Switching is written in RISC-V assembly and counted on `rv`; deciding is studied with a simulator, and the classic policies are compared and some of them proved optimal or fair.

**You already know.**

In the Year 2 volume a process is a running program with its own memory; it asks the operating system for a service with a system call, and the processor runs the operating system’s code in [kernel](#def-b3-kernel-and-scheduling-kernel) mode, where privileged instructions are allowed, then returns to user mode.

## 10.1 The kernel

**Definition 10.1 (Kernel, monolithic kernel, microkernel).**

The *kernel* is the part of the operating system that runs in kernel mode: it alone touches the devices, the memory map and the processor’s privileged state, and every process reaches them through it. A *monolithic kernel* runs all its services (file systems, device drivers, network stack, scheduler) in kernel mode, in one address space. A *microkernel* keeps in kernel mode only what needs the privilege, address spaces, threads and messages between them, and runs the other services as ordinary processes that exchange messages.

The trade is speed against isolation. In a [monolithic kernel](#def-b3-kernel-and-scheduling-kernel) a call from the file system to a disk driver is a function call; in a [microkernel](#def-b3-kernel-and-scheduling-kernel) it is two messages, each crossing into the [kernel](#def-b3-kernel-and-scheduling-kernel) and out. In exchange, a faulty driver in a [microkernel](#def-b3-kernel-and-scheduling-kernel) crashes one process, which can be restarted, where in a [monolithic kernel](#def-b3-kernel-and-scheduling-kernel) it can corrupt anything. The system-call interface is the same in both: a table, indexed by the number the program puts in a register, of the [kernel](#def-b3-kernel-and-scheduling-kernel)’s functions. `rv` has such a table (`Machine.ecalls`), with print, read, `sbrk` and exit.

## 10.2 Interrupts and traps

**Definition 10.2 (Interrupt, trap, hardware exception, interrupt vector, timer interrupt).**

A *trap* is a transfer of control from the running program to the [kernel](#def-b3-kernel-and-scheduling-kernel), made by the processor itself in the middle of an instruction stream. It is caused either by the instruction being executed, a *hardware exception* (an illegal instruction, a load from an address that faults, a system call), or by an event outside the program, an *interrupt* (a device has data, a timer has expired). The *interrupt vector* is the address, or table of addresses, the processor jumps to on a trap. A *timer interrupt* is an interrupt raised when a clock reaches a value the [kernel](#def-b3-kernel-and-scheduling-kernel) set.

On RISC-V, a [trap](#def-b3-kernel-and-scheduling-interrupt) into machine mode writes the address of the interrupted instruction, or of the one that caused the exception, into the register `mepc`, and a code for the cause into `mcause`, whose top bit says whether it was an [interrupt](#def-b3-kernel-and-scheduling-interrupt); the processor then jumps to the address configured in `mtvec`. The instruction `mret` returns to the address in `mepc`. The machine [timer interrupt](#def-b3-kernel-and-scheduling-interrupt) becomes pending when the free-running counter `mtime` reaches the value of `mtimecmp`, which the [kernel](#def-b3-kernel-and-scheduling-kernel) writes to choose the next tick.

![A trap. The processor does three things by itself, all in one step: it records where the program was and why it stopped, and jumps to the kernel’s entry point. The kernel saves the registers the handler will use, handles the event, restores registers (perhaps those of another process), and returns. For a system call, the kernel adds 4 to the saved address, so that the program resumes after its ecall.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-kernel-and-scheduling/fig-5a5b08b69e62.svg)

*A [trap](#def-b3-kernel-and-scheduling-interrupt). The processor does three things by itself, all in one step: it records where the program was and why it stopped, and jumps to the [kernel](#def-b3-kernel-and-scheduling-kernel)’s entry point. The [kernel](#def-b3-kernel-and-scheduling-kernel) saves the registers the handler will use, handles the event, restores registers (perhaps those of another process), and returns. For a system call, the [kernel](#def-b3-kernel-and-scheduling-kernel) adds 4 to the saved address, so that the program resumes after its `ecall`.*

**Definition 10.3 (Preemption, context switch, process control block).**

*Preemption* is the [kernel](#def-b3-kernel-and-scheduling-kernel) taking the processor away from a running process that did not ask to give it up. A *context switch* saves the state of the running process (its registers and program counter) and loads the saved state of another, which then resumes where it stopped. The *process control block* is the [kernel](#def-b3-kernel-and-scheduling-kernel)’s record of a process: its saved state, its memory map, its open files, its scheduling information.

Without the timer, a program that never makes a system call and never faults keeps the processor for ever. With it, the [kernel](#def-b3-kernel-and-scheduling-kernel) gets control back at every tick, whatever the program does. `rv` has no timer, but a [kernel](#def-b3-kernel-and-scheduling-kernel) written in Python around it can count the instructions and take control every 50 ([Listing 10.1](#lst-b3-kernel-and-scheduling-timer)). The two programs it runs in turn are loops that never give the processor up (`two_loops.S`).

```python
"""timer.py -- a kernel in Python around the rv machine. A timer interrupt every 50
instructions saves the running process's registers and pc in its process control
block, picks the next ready process in turn, and restores its registers: preemption,
with no help from the programs. Each exit ecall ends only the process that makes it."""
from rv import Machine

QUANTUM = 50
m = Machine(open("two_loops.S").read())
pcbs = []  # process control blocks: name, saved pc, saved registers, still running?
for name in ("a", "b"):
    pc = m.prog.symbols[f"task_{name}"]
    regs = list(m.x)
    regs[2] = 0x7FFFFFF0 - 4096 * len(pcbs)  # sp: each process its own stack
    pcbs.append({"name": name, "pc": pc, "regs": regs, "alive": True})
running, switches = 0, 0


def exit_process(machine):  # ecall 10: this process is done, the machine goes on
    pcbs[running]["alive"] = False


m.ecalls[10] = exit_process
m.pc, m.x[:] = pcbs[0]["pc"], pcbs[0]["regs"]
since = 0
while any(p["alive"] for p in pcbs):
    m.step()
    since += 1
    if since == QUANTUM or not pcbs[running]["alive"]:  # timer, or the process ended
        pcbs[running]["pc"], pcbs[running]["regs"] = m.pc, list(m.x)  # save
        nxt = running
        for k in range(1, len(pcbs) + 1):  # round robin over the live processes
            if pcbs[(running + k) % len(pcbs)]["alive"]:
                nxt = (running + k) % len(pcbs)
                break
        if nxt != running:
            switches += 1
        running, since = nxt, 0
        m.pc, m.x[:] = pcbs[running]["pc"], pcbs[running]["regs"]  # restore
print("printed:", m.output_text)
print(f"{m.steps} instructions, {switches} switches")
```

***Listing 10.1.** A preemptive [kernel](#def-b3-kernel-and-scheduling-kernel) in Python around `rv`: one [process control block](#def-b3-kernel-and-scheduling-switch) per program, a timer every 50 instructions, and a [context switch](#def-b3-kernel-and-scheduling-switch) that saves and restores all 32 registers and the program counter. code/bachelor-3/10-kernel-and-scheduling/listings/timer.py*

```
$ python timer.py
printed: aaabbbaabbaabbaabbaaabbb
534 instructions, 11 switches
```

***Output 10.1.** Two loops that each print their letter 12 times, interleaved by the timer: neither program contains a single instruction that hands control to the other.*

## 10.3 The context switch

The [kernel](#def-b3-kernel-and-scheduling-kernel)’s switch, as [Listing 10.1](#lst-b3-kernel-and-scheduling-timer) does it, saves all the registers, because the program was stopped between any two instructions. A switch the program asks for, by calling a function, needs less: by the calling convention, the caller has already saved whatever it needs among the registers a call may change. Only the registers a callee must preserve, `s0`–`s11`, with `ra` and `sp`, must survive. That is the switch at the heart of most [kernels](#def-b3-kernel-and-scheduling-kernel), called by the [kernel](#def-b3-kernel-and-scheduling-kernel)’s own code: the [trap](#def-b3-kernel-and-scheduling-interrupt) entry saves the interrupted program’s registers on the [kernel](#def-b3-kernel-and-scheduling-kernel) stack of that process, and the switch then only has to move from one [kernel](#def-b3-kernel-and-scheduling-kernel) stack to another.

**You already know.**

In the Year 2 volume’s RISC-V calling convention, `a0`–`a7` carry arguments and results, `ra` the return address and `sp` the stack pointer; a function may change `t0`–`t6` and `a0`–`a7`, and must leave `s0`–`s11` and `sp` as it found them.

[Listing 10.2](#lst-b3-kernel-and-scheduling-coroutines) runs two coroutines, each on its own stack and each counting in `s1`; [Listing 10.3](#lst-b3-kernel-and-scheduling-switch) is the switch, 28 stores and loads and a `ret`. The `ret` returns to the address in the *loaded* `ra`: into the other coroutine, just after the call by which it gave the processor up.

```text
task_a: li   s1, 1              # A counts 1, 2, 3 in s1
loop_a: li   a0, 'A'
        call show
        la   a0, ctx_a
        la   a1, ctx_b
        call switch            # let B run
        addi s1, s1, 1
        li   t0, 4
        blt  s1, t0, loop_a
        la   a0, ctx_a
        la   a1, ctx_main
        call switch            # A is done: back to main, for good

task_b: li   s1, 10             # B counts 10, 20, 30 in its own s1
loop_b: li   a0, 'B'
        call show
        la   a0, ctx_b
        la   a1, ctx_a
        call switch
        addi s1, s1, 10
        j    loop_b
```

***Listing 10.2.** Two coroutines that pass the processor to each other; each counts in `s1`. code/bachelor-3/10-kernel-and-scheduling/listings/switch.S*

```text
# switch(a0 = where to save this context, a1 = the context to resume)
switch: sw   ra, 0(a0)
        sw   sp, 4(a0)
        sw   s0, 8(a0)
        sw   s1, 12(a0)
        sw   s2, 16(a0)
        sw   s3, 20(a0)
        sw   s4, 24(a0)
        sw   s5, 28(a0)
        sw   s6, 32(a0)
        sw   s7, 36(a0)
        sw   s8, 40(a0)
        sw   s9, 44(a0)
        sw   s10, 48(a0)
        sw   s11, 52(a0)
        lw   ra, 0(a1)
        lw   sp, 4(a1)
        lw   s0, 8(a1)
        lw   s1, 12(a1)
        lw   s2, 16(a1)
        lw   s3, 20(a1)
        lw   s4, 24(a1)
        lw   s5, 28(a1)
        lw   s6, 32(a1)
        lw   s7, 36(a1)
        lw   s8, 40(a1)
        lw   s9, 44(a1)
        lw   s10, 48(a1)
        lw   s11, 52(a1)
        ret                     # to the resumed context's ra: where it called switch
```

***Listing 10.3.** The switch: save the callee-saved registers, `ra` and `sp` of one context, load the other’s, return into it. code/bachelor-3/10-kernel-and-scheduling/listings/switch.S*

![The first switch from A to B in . A’s registers go into ctx_a: its ra is the instruction after its call to switch, its s1 is 1. B’s context was prepared by main: ra = task_b, sp = the top of B’s stack, the rest 0. The ret at the end of the switch therefore starts B.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-kernel-and-scheduling/fig-17f0d8f7c863.svg)

*The first switch from A to B in [Listing 10.2](#lst-b3-kernel-and-scheduling-coroutines). A’s registers go into `ctx_a`: its `ra` is the instruction after its call to `switch`, its `s1` is 1. B’s context was prepared by `main`: `ra` = `task_b`, `sp` = the top of B’s stack, the rest 0. The `ret` at the end of the switch therefore starts B.*

```
$ python -m rv run --stats switch.S
A1
B10
A2
B20
A3
B30
--- stats ---
instructions       371
loads              112
stores             116
branches             3  (2 taken)
jumps               30
ecalls              19
```

***Output 10.2.** The coroutines take turns. Each of the 8 switches executes 29 instructions, 14 stores and 14 loads: the 112 loads of the run are all in the switch.*

Of the 371 instructions of the run, 232 are in the 8 switches. A real [kernel](#def-b3-kernel-and-scheduling-kernel)’s switch also changes the memory map when the two processes differ, which has an indirect cost far larger than its instructions, since the caches and the address translations of the old process are of no use to the new one: chapter [11](https://one-course.com/books/computer-science/5/en/chapter/11-virtual-memory#ch-b3-virtual-memory) returns to it. The C library offers the same mechanism to programs as `ucontext`: `getcontext` captures the current context, `makecontext` prepares one that will run a function on a given stack, and `swapcontext` saves one and resumes the other ([Listing 10.4](#lst-b3-kernel-and-scheduling-ucontext)). POSIX marked these functions obsolescent in 2004 and later removed them, advising threads instead; the GNU C library still provides them.

```c
static void task_a(void)
{
    for (int i = 1; i <= 3; i++) {
        printf("A%d\n", i);
        swapcontext(&a_ctx, &b_ctx);  /* save A, resume B */
    }
}  /* returning resumes uc_link: main */

static void task_b(void)
{
    for (int i = 10;; i += 10) {
        printf("B%d\n", i);
        swapcontext(&b_ctx, &a_ctx);
    }
}

static void prepare(ucontext_t *c, char *stack, size_t size, void (*f)(void))
{
    getcontext(c);
    c->uc_stack.ss_sp = stack;
    c->uc_stack.ss_size = size;
    c->uc_link = &main_ctx;  /* where to go when f returns */
    makecontext(c, f, 0);
}

int main(void)
{
    prepare(&a_ctx, a_stack, sizeof a_stack, task_a);
    prepare(&b_ctx, b_stack, sizeof b_stack, task_b);
    swapcontext(&main_ctx, &a_ctx);
    printf("back in main\n");
    return 0;
}
```

***Listing 10.4.** The same ping-pong with `ucontext`. When `task_a` returns, the context in `uc_link`, `main`’s, resumes. code/bachelor-3/10-kernel-and-scheduling/listings/ucontext_switch.c*

```
$ gcc -std=c17 -O2 -Wall -Wextra -o ucontext_switch ucontext_switch.c -lm && ./ucontext_switch
A1
B10
A2
B20
A3
B30
back in main
```

***Output 10.3.** The ping-pong in C.*

## 10.4 Scheduling policies

**Definition 10.4 (Turnaround, waiting and response time).**

For a job that arrives at time $a$, needs $b$ units of processor time (its *burst*), first runs at time $f$ and finishes at time $c$: its *turnaround time* is $c - a$, its *waiting time* $c - a - b$, the time it spent ready but not running, and its *response time* $f - a$.

**Definition 10.5 (Scheduling policies).**

A *scheduling policy* chooses which ready job runs next, and for how long. *First come first served* runs the jobs to completion in their order of arrival. *Shortest job first* runs to completion the ready job with the smallest burst. *Shortest remaining time first* is its preemptive form: whenever a job arrives, the job with the least work left runs. *Round robin* runs the ready jobs in turn, each for at most a *time slice* $q$, the *quantum*, then puts it at the back of the queue.

`sched.py` simulates them ([Listing 10.5](#lst-b3-kernel-and-scheduling-sim)): time advances from one decision to the next, a job that arrives during a turn joins the queue before the job that was running, and a change of job can cost `switch` units of time.

```python
def simulate(jobs, pick=fifo, quantum=None, preempt=False, switch=0):
    """quantum: at most that long per turn (round robin);
    preempt: stop at every arrival."""
    pending = sorted(jobs, key=lambda j: j.arrival)
    left = {j.name: j.burst for j in jobs}
    ready, r, t, last = [], Result(), 0, None

    def admit(now):
        while pending and pending[0].arrival <= now:
            ready.append(pending.pop(0).name)

    while pending or ready:
        admit(t)
        if not ready:
            t = pending[0].arrival
            continue
        j = pick(ready, left)
        if last is not None and last != j and switch:
            r.gantt.append((t, t + switch, "*"))
            t += switch
            admit(t)
        r.first.setdefault(j, t)
        run = left[j] if quantum is None else min(quantum, left[j])
        if preempt and pending:
            run = min(run, max(pending[0].arrival - t, 1))
        if r.gantt and r.gantt[-1][2] == j and r.gantt[-1][1] == t:
            r.gantt[-1] = (r.gantt[-1][0], t + run, j)  # the same job goes on
        else:
            r.gantt.append((t, t + run, j))
        t += run
        left[j] -= run
        admit(t)  # arrivals during the turn queue before the job that ran
        if left[j] == 0:
            r.finish[j] = t
        else:
            ready.append(j)
        last = j
    return r
```

***Listing 10.5.** The simulator. The policy is the function `pick`, plus a quantum and whether arrivals preempt. code/bachelor-3/10-kernel-and-scheduling/listings/sched.py*

```
$ python fcfs_sjf.py
policy  turnaround  waiting  response
FCFS          16.6     11.0      11.0
SJF           13.4      7.8       7.8
SRTF          12.0      6.4       3.8
RR q=3        19.8     14.2       4.2
FCFS: A[0,8) B[8,12) C[12,21) D[21,26) E[26,28)
SJF: A[0,8) E[8,10) B[10,14) D[14,19) C[19,28)
SRTF: A[0,1) B[1,5) D[5,6) E[6,8) D[8,12) A[12,19) C[19,28)
RR q=3: A[0,3) B[3,6) C[6,9) D[9,12) A[12,15) E[15,17) B[17,18) C[18,21) D[21,23) A[23,25) C[25,28)
```

***Output 10.4.** Five jobs, A to E, arriving at times 0, 1, 2, 3, 6 with bursts 8, 4, 9, 5, 2, under four policies: the averages, then each timeline as `job[start,end)`.*

![The timelines of . Shortest job first moves E, the shortest, before B, D and C; shortest remaining time first also interrupts A, at 1, and D, at 6. Round robin gives every job the processor within 9 units of its arrival, at the price of finishing A, B and C later than first come first served does.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-kernel-and-scheduling/fig-32c0ac138ca7.svg)

*The timelines of [Output 10.4](#out-b3-kernel-and-scheduling-policies). [Shortest job first](#def-b3-kernel-and-scheduling-policies) moves E, the shortest, before B, D and C; [shortest remaining time first](#def-b3-kernel-and-scheduling-policies) also [interrupts](#def-b3-kernel-and-scheduling-interrupt) A, at 1, and D, at 6. Round robin gives every job the processor within 9 units of its arrival, at the price of finishing A, B and C later than [first come first served](#def-b3-kernel-and-scheduling-policies) does.*

[Shortest remaining time first](#def-b3-kernel-and-scheduling-policies) has the best averages, and round robin the worst turnaround but a [response time](#def-b3-kernel-and-scheduling-metrics) close to the best. A policy is a choice of what to optimise. For [waiting time](#def-b3-kernel-and-scheduling-metrics), with all jobs present at once, [shortest job first](#def-b3-kernel-and-scheduling-policies) is the best possible order.

**You already know.**

The Year 1 volume proved greedy algorithms optimal by exchange: take an optimal solution that differs from the greedy one, swap two elements to make it closer to the greedy one, and show that the swap does not make it worse.

**Theorem 10.6 (Shortest job first is optimal).**

For jobs all present at time 0, running them to completion in increasing order of burst minimises the average [waiting time](#def-b3-kernel-and-scheduling-metrics) over all orders.

**Proof.** In the order $b_1, b_2, \dots, b_n$, the $k$-th job waits $b_1 + \dots + b_{k-1}$, so the total [waiting time](#def-b3-kernel-and-scheduling-metrics) is $\sum_{k} (n - k)\, b_k$: the job in position $k$ delays the $n - k$ jobs after it. Take an order in which two neighbours are out of order, $b_k > b_{k+1}$. Swapping them changes the total by $(n - k) b_{k+1} + (n - k - 1) b_k - (n - k) b_k - (n - k - 1) b_{k+1} = b_{k+1} - b_k < 0$. So an optimal order has no such pair: it is sorted. Splitting the processor between jobs cannot help either, since it only delays the job that would have finished first. ∎

`test_sched.py` checks the theorem against every order on 200 random sets of jobs. With arrivals at different times, [shortest remaining time first](#def-b3-kernel-and-scheduling-policies) is the preemptive counterpart, and [Output 10.4](#out-b3-kernel-and-scheduling-policies) shows it ahead. Both need the bursts in advance, which a [kernel](#def-b3-kernel-and-scheduling-kernel) does not know; it can only estimate each process’s next burst from its past ones, for instance by an exponential average. And both can starve a long job for as long as short ones keep arriving (exercise [10.12](#exo-b3-kernel-and-scheduling-12)). Round robin cannot starve anyone, and bounds the [response time](#def-b3-kernel-and-scheduling-metrics).

**Theorem 10.7 (Round robin’s response time).**

With $n$ jobs ready at time 0, quantum $q$ and no switching cost, every job first runs by time $(n - 1)q$.

The proof is exercise [10.8](#exo-b3-kernel-and-scheduling-8). The quantum trades response against throughput: each switch costs time, and the weekend problem measures how much.

**Definition 10.8 (Multilevel feedback queue).**

A *multilevel feedback queue* keeps several round-robin queues of decreasing priority, with longer quanta lower down. A new job enters the top queue; a job that uses up its whole quantum moves down one level; a job that gives the processor up before, to wait for input, keeps its level. The highest non-empty queue runs, and a job arriving in a higher queue preempts a lower one.

The policy learns what it cannot be told: a job that keeps computing reveals itself as a long one and sinks, and an interactive job, which computes briefly between inputs, stays at the top and responds at once ([Output 10.5](#out-b3-kernel-and-scheduling-mlfq)). Two weaknesses are told, not simulated: many interactive jobs can starve the bottom queue, the remedy is to move every job back to the top now and then; and a job that gives up the processor just before its quantum ends stays on top for ever, unless the scheduler counts the processor time used at a level rather than per turn.

```python
while any(bursts.values()):
    for name in JOBS:  # a job that becomes ready joins the back of its level's queue
        if ready_at[name] is not None and ready_at[name] <= t:
            queues[level[name]].append(name)
            if name == "edit":
                waited.append(-t)  # completed when it runs
            ready_at[name] = None
    if current and any(queues[:level[current]]):  # preempted by a higher level
        queues[level[current]].insert(0, current)
        current = None
    if current is None:
        busy = [q for q in queues if q]
        if not busy:
            t += 1
            continue
        current, used = busy[0].pop(0), 0
        if current == "edit":
            waited[-1] += t
        trace.append([t, t, current, level[current]])
    t, used = t + 1, used + 1
    trace[-1][1] = t
    bursts[current][0] -= 1
    if bursts[current][0] == 0:  # the burst is over: wait for input, keep the level
        bursts[current].pop(0)
        ready_at[current] = t + WAIT if bursts[current] else None
        current = None
    elif used == QUANTA[level[current]]:
        level[current] = min(level[current] + 1, len(QUANTA) - 1)
        queues[level[current]].append(current)
        current = None
```

***Listing 10.6.** Three levels, quanta 2, 4 and 8, simulated one time unit at a time. code/bachelor-3/10-kernel-and-scheduling/listings/mlfq.py*

```
$ python mlfq.py
  0-2   render level 0
  2-3   edit   level 0
  3-7   render level 1
  7-8   edit   level 0
  8-12  render level 2
 12-13  edit   level 0
 13-17  render level 2
 17-18  edit   level 0
 18-22  render level 2
 22-23  edit   level 0
 23-27  render level 2
 27-28  edit   level 0
... 18 turns in all, the last ends at t = 48
edit's wait from ready to running: 1 0 0 0 0 0 0 0
```

***Output 10.5.** A long computation, `render`, and an editor, `edit`, which needs one unit after each keystroke. `render` sinks to the bottom level in two turns; `edit` stays on top and, after the first keystroke, runs at once.*

**Definition 10.9 (Fair-share scheduling: lottery and stride).**

*Fair-share scheduling* gives each client a share of the processor proportional to the number of tickets it holds. *Lottery scheduling* draws a ticket at random at each quantum, and its holder runs. *Stride scheduling* gives each client a *stride*, a large constant divided by its tickets, and a *pass*, initially its stride; at each quantum the client with the least pass runs and its pass grows by its stride.

```python
def lottery():  # draw a ticket at random; its holder runs
    k = rng.randrange(TOTAL)
    for name, n in TICKETS.items():
        if k < n:
            return name
        k -= n


stride = {name: 10_000 // n for name, n in TICKETS.items()}  # big number / tickets
passes = dict(stride)


def stride_next():  # the least pass runs, and its pass advances by its stride
    name = min(passes, key=lambda c: (passes[c], c))
    passes[name] += stride[name]
    return name

```

***Listing 10.7.** A lottery and a stride scheduler for the same three clients. code/bachelor-3/10-kernel-and-scheduling/listings/stride.py*

```
$ python stride.py
quanta          ideal A B C        lottery         stride
    10        2.5 1.25 6.25          4 0 6          2 1 7
   100         25 12.5 62.5        30 9 61       25 12 63
  1000          250 125 625    261 140 599    250 125 625
largest error over the 1,000 quanta: lottery 27.62, stride 0.88 quanta
```

***Output 10.6.** Quanta received by A, B and C, holding 100, 50 and 250 tickets. The lottery is right on average; stride is within a quantum at every checkpoint.*

**Theorem 10.10 (Stride scheduling is nearly exact).**

Let $k$ clients hold $t_1, \dots, t_k$ tickets, $T = \sum_i t_i$, with exact strides $s_i = L/t_i$ and initial passes $s_i$. After $N$ quanta, client $i$ has received $n_i$ quanta with

$$
-1 < n_i - N\frac{t_i}{T} \le (k - 1)\frac{t_i}{T}.
$$

In particular the error is less than one quantum for two clients, and less than $k - 1$ for any number.

The proof is exercise [10.10](#exo-b3-kernel-and-scheduling-10). The lottery’s error after $t$ quanta grows like $\sqrt{t}$: its largest error over 1,000 quanta was 27.6 quanta, the stride scheduler’s 0.88.

**Definition 10.11 (Real-time scheduling, deadline, rate-monotonic, earliest deadline first).**

*Real-time scheduling* must finish each job by its *deadline*, a time fixed in advance. A periodic task $i$ releases a job every $T_i$ units, needing $C_i$ units, due before the next release. *Rate-monotonic scheduling* gives each task a fixed priority, higher for a shorter period. *Earliest deadline first* runs at every moment the ready job whose deadline is nearest.

Two results of Liu and Layland are stated here, with the utilisation $U = \sum_i C_i / T_i$, the fraction of the processor the tasks need. [Rate-monotonic scheduling](#def-b3-kernel-and-scheduling-realtime) meets every [deadline](#def-b3-kernel-and-scheduling-realtime) if $U \le n(2^{1/n} - 1)$ for $n$ tasks, a bound that decreases towards $\ln 2 \approx 0.69$; [earliest deadline first](#def-b3-kernel-and-scheduling-realtime) meets every [deadline](#def-b3-kernel-and-scheduling-realtime) whenever $U \le 1$, which no policy can improve on. Exercise [10.11](#exo-b3-kernel-and-scheduling-11) proves the first bound for two tasks.

**History — Schedulers.**

Fernando Corbató, Marjorie Merwin-Daggett and Robert Daley described an experimental time-sharing system in May 1962. C. L. Liu and James Layland published their scheduling algorithms for hard-real-time multiprogramming in January 1973. Carl Waldspurger and William Weihl presented [lottery scheduling](#def-b3-kernel-and-scheduling-share) in 1994.

## 10.5 Exercises

**Exercise 10.1 ★.**

Draw the round-robin timeline with $q = 2$ for P (arrives at 0, burst 5), Q (1, 3) and R (2, 1). When does each job finish?

**Solution of Exercise 10.1.**

P runs $[0, 2)$; Q arrived at 1 and R at 2, both before P’s turn ends, so the queue is Q, R, P. Q runs $[2, 4)$, R $[4, 5)$ and finishes, P $[5, 7)$, Q $[7, 8)$ and finishes, P $[8, 9)$ and finishes. R finishes at 5, Q at 8, P at 9 (`test_exercise_1_round_robin_by_hand`).

**Exercise 10.2 ★.**

Four jobs present at time 0 have bursts 6, 2, 8 and 3. Give the average [waiting time](#def-b3-kernel-and-scheduling-metrics) under [first come first served](#def-b3-kernel-and-scheduling-policies) in that order, and under [shortest job first](#def-b3-kernel-and-scheduling-policies).

**Solution of Exercise 10.2.**

In the given order the waits are 0, 6, 8 and 16: average 7.5. [Shortest job first](#def-b3-kernel-and-scheduling-policies) runs 2, 3, 6, 8, with waits 0, 2, 5 and 11: average 4.5.

**Exercise 10.3 ★.**

Which of these transfer control to the RISC-V [kernel](#def-b3-kernel-and-scheduling-kernel) by a [trap](#def-b3-kernel-and-scheduling-interrupt), and which kind: an `ecall`; an integer division by zero; a load from address 0; the timer reaching `mtimecmp`; a key pressed; an illegal instruction; a `ret`?

**Solution of Exercise 10.3.**

`ecall`: a [trap](#def-b3-kernel-and-scheduling-interrupt), an exception requested by the program. Integer division by zero: no [trap](#def-b3-kernel-and-scheduling-interrupt) at all; RISC-V defines its result, $-1$ for the quotient. A load from address 0: a [trap](#def-b3-kernel-and-scheduling-interrupt), an exception (an access fault). The timer reaching `mtimecmp`: a [trap](#def-b3-kernel-and-scheduling-interrupt), an [interrupt](#def-b3-kernel-and-scheduling-interrupt). A key pressed: an [interrupt](#def-b3-kernel-and-scheduling-interrupt), from the keyboard’s controller. An illegal instruction: an exception. A `ret`: an ordinary jump, no [trap](#def-b3-kernel-and-scheduling-interrupt).

**Exercise 10.4 ★.**

In `switch.S`, `main` switches to `ctx_b` instead of `ctx_a`. Predict the output.

**Solution of Exercise 10.4.**

`B10`, `A1`, `B20`, `A2`, `B30`, `A3`, `B40`: B now starts, and A, after printing A3, increments its counter to 4 and switches to `main`, which exits, after B has printed one more line (`test_exercise_4_b_first`).

**Exercise 10.5 ★★.**

`switch_bug.S` is `switch.S` with a switch that neither saves nor loads `s1`. It prints only two lines. Explain them, and why the program then stops normally.

```
$ python -m rv run switch_bug.S
A1
B10
```

***Output 10.7.** The switch without `s1`.*

**Solution of Exercise 10.5.**

A prints A1 and switches to B; `s1` is not saved, so it still holds A’s 1, but B sets it to 10 and prints B10. B switches back to A without saving `s1` either, and A resumes with B’s 10 in `s1`. A adds 1, gets 11, which is not below 4, so its loop ends after one line: A switches to `main`, which exits normally. Nothing faults; the program is simply wrong, which is why a forgotten register in a switch is hard to find. The fix puts back the store `sw s1, 12(a0)` and the load `lw s1, 12(a1)`.

**Exercise 10.6 ★★.**

Write non-preemptive priority scheduling with aging: a lower number runs first, and a job’s priority improves by 1 for every `age` units it has waited. Test it on a low-priority job of 3 units at time 0 and ten high-priority jobs of 3 units arriving every 3 units: without aging, when does the low one finish?

**Solution of Exercise 10.6.**

`exercises/ex6_aging.py` picks the ready job with the least `prio - waited // age`. Without aging (a huge `age`), each high-priority job arrives as the previous one finishes, so the low one runs only after all ten: it finishes at 33. With `age` = 3 it gains a level every 3 units and runs much earlier (`test_exercise_6_aging_lets_the_low_priority_job_run`).

**Exercise 10.7 ★★.**

Show that the ratio of the average [waiting time](#def-b3-kernel-and-scheduling-metrics) under [first come first served](#def-b3-kernel-and-scheduling-policies) to that under [shortest job first](#def-b3-kernel-and-scheduling-policies), for jobs all present at time 0, can be as large as you like.

**Solution of Exercise 10.7.**

Take one job of burst $M$ first and $n - 1$ jobs of burst 1. [First come first served](#def-b3-kernel-and-scheduling-policies) makes each short job wait at least $M$: total at least $(n - 1)M$. [Shortest job first](#def-b3-kernel-and-scheduling-policies) runs the short ones first: total $0 + 1 + \dots + (n - 1) = n(n - 1)/2$. The ratio is at least $2M/n$, as large as you like for a fixed $n$ when $M$ grows.

**Exercise 10.8 ★★.**

Prove [Theorem 10.7](#thm-b3-kernel-and-scheduling-rr).

**Solution of Exercise 10.8.**

At time 0 the queue holds the $n$ jobs. A job runs at most $q$ units per turn, then goes to the back, and nothing arrives. So the $k$-th job in the queue starts after the $k - 1$ jobs before it have had one turn each, each of at most $q$ units: it first runs by $(k - 1)q \le (n - 1)q$. `test_round_robin_response_bound` checks it on 200 random sets.

**Exercise 10.9 ★★.**

From [Listing 10.3](#lst-b3-kernel-and-scheduling-switch), count the instructions one switch executes, including those that prepare and make the call, and check the total against [Output 10.2](#out-b3-kernel-and-scheduling-switchcount).

**Solution of Exercise 10.9.**

29 instructions in the switch (14 stores, 14 loads, `ret`) and 5 to call it: each `la` is two instructions on `rv` (`auipc` and `addi`) and the `call` one `jal`, so 34 per switch in all. The run makes 8 switches: `main` to A, three from A to B, three from B to A, and A to `main`. That is $8 \times 29 = 232$ of the 371 instructions in the switch itself, and $8 \times 14 = 112$ loads, all the loads of the run (`test_switch_output_and_cost`).

**Exercise 10.10 ★★★.**

Prove [Theorem 10.10](#thm-b3-kernel-and-scheduling-stride). (Show first that the passes always lie within one stride of the least pass.) Check the bound against [Output 10.6](#out-b3-kernel-and-scheduling-stride).

**Solution of Exercise 10.10.**

Client $i$’s pass after $n_i$ runs is $p_i = (n_i + 1)s_i$. Let $P$ be the least pass at some moment. The least pass never decreases: a step raises the pass of the client that held it and leaves the others alone. If client $i$ has run, its pass before its last run, $p_i - s_i$, was the least pass at that time, so $p_i - s_i \le P$; if it has not run, $p_i - s_i = 0 \le P$. Hence $P \le p_i \le P + s_i$, that is $n_i = x t_i - e_i$ with $x = P/L$ and $0 \le e_i \le 1$. Summing, $N = xT - E$ with $E = \sum_j e_j$, so $x = (N + E)/T$ and

$$
n_i - N\frac{t_i}{T} = E\frac{t_i}{T} - e_i.
$$

Since $E \ge e_i$, this is at least $e_i(t_i/T - 1) > -1$ (if $e_i = 0$ it is $\ge 0$). Since $E \le e_i + (k - 1)$, it is at most $e_i(t_i/T - 1) + (k - 1)t_i/T \le (k - 1)t_i/T$. For two clients the upper bound is $t_i/T < 1$. In [Output 10.6](#out-b3-kernel-and-scheduling-stride) the bounds are $0.5$, $0.25$ and $1.25$ for A, B and C; the largest error measured is 0.88 (`test_stride_error_below_one_quantum`).

**Exercise 10.11 ★★★.**

Two periodic tasks with periods $T_1 < T_2$ run under [rate-monotonic scheduling](#def-b3-kernel-and-scheduling-realtime). Prove that every [deadline](#def-b3-kernel-and-scheduling-realtime) is met when $C_1/T_1 + C_2/T_2 \le 2(\sqrt{2} - 1) \approx 0.828$.

**Solution of Exercise 10.11.**

Task 1 has the higher priority and is never delayed; it meets its [deadlines](#def-b3-kernel-and-scheduling-realtime) if $C_1 \le T_1$. Task 2’s job released at 0 (the worst case, released with task 1) is delayed only by task 1. Let $F = \lfloor T_2/T_1 \rfloor$. If $C_1 \le T_2 - F T_1$, the last job of task 1 before $T_2$ finishes before $T_2$, and task 2 needs $C_2 \le T_2 - (F + 1)C_1$. Otherwise it needs $C_2 \le F(T_1 - C_1)$. In each case take $C_2$ as large as allowed and minimise $U = C_1/T_1 + C_2/T_2$ over $C_1$: $U$ is linear in $C_1$ on each side, so its minimum is at $C_1 = T_2 - F T_1$, where $U = 1 - f(1 - f)/(F + f)$ with $f = T_2/T_1 - F$. This is least for $F = 1$, and then $1 - f(1 - f)/(1 + f)$ is minimised at $f = \sqrt{2} - 1$, giving $U = 2(\sqrt{2} - 1)$. Any set with a smaller utilisation therefore meets all [deadlines](#def-b3-kernel-and-scheduling-realtime).

**Exercise 10.12 ★★★.**

Build a workload in which [shortest remaining time first](#def-b3-kernel-and-scheduling-policies) makes a job of 20 units wait as long as you like, then fix it with aging: the key becomes the work left minus the time waited divided by `age`. How long does the long job take with 100 short jobs of 2 units, with and without aging, $\mathit{age} = 2$?

**Solution of Exercise 10.12.**

`exercises/ex12_starve.py`: the long job arrives at 0, and a short job of 2 units arrives every 2 units from time 1. Each arriving short job has less work left than the long one, so the long job runs one unit, then waits until the stream ends: with 100 short jobs it finishes at 220, and with $n$ at $2n + 20$, as late as you like. With aging, $\mathit{age} = 2$, every 2 units waited take one unit off its key. At time 35 it has waited 34 units and its key is $19 - 17 = 2$, equal to a newly arrived short job’s, and the tie goes to the earlier arrival. Once it runs, its waiting stops and its work left falls, so its key only decreases: it runs to the end and finishes at 54 (`test_exercise_12_starvation_and_its_fix`).

## 10.6 Weekend problem

**Problem 10.1.**

Weekend problem — The print shop’s queue

The town’s print shop has one machine and a queue. Sixty jobs arrive at random, on average one every 45 units of time; four in five are small (2 to 12 units), one in five long (40 to 120). Changing from one job to another costs $s = 1$ unit. [Output 10.8](#out-b3-kernel-and-scheduling-pb) runs [first come first served](#def-b3-kernel-and-scheduling-policies), [shortest job first](#def-b3-kernel-and-scheduling-policies), and round robin for every quantum from 1 to 20; the figure after it plots the averages.

```python
"""rr_quantum.py -- the weekend problem: the print shop's jobs under round robin with a
switch cost of s = 1, for quanta 1 to 20, against first come first served and
shortest job first, which pay the same switch cost from one job to the next."""
import random

from sched import Job, fifo, shortest, simulate

rng = random.Random(2026)
jobs, t = [], 0
for k in range(60):  # one job every 45 units on average; one in five is long
    t += round(rng.expovariate(1 / 45))
    burst = rng.randint(2, 12) if rng.random() < 0.8 else rng.randint(40, 120)
    jobs.append(Job(f"J{k}", t, burst))
work = sum(j.burst for j in jobs)
load = work / jobs[-1].arrival
print(f"{len(jobs)} jobs, {work} units of work, last arrival {jobs[-1].arrival},"
      f" load {load:.2f}")
for name, pick in (("FCFS", fifo), ("SJF", shortest)):
    turn, _, resp = simulate(jobs, pick, switch=1).averages(jobs)
    print(f"{name:<4}  turnaround {turn:6.1f}  response {resp:5.1f}")
head = f"{'turnaround':>10} {'response':>8} {'switches':>8}"
head += f" {'overhead':>8} {'s/(q+s)':>7}"
print(f"{'q':>3} {head} {'load(q+s)/q':>11}")
for q in range(1, 21):
    r = simulate(jobs, fifo, quantum=q, switch=1)
    turn, _, resp = r.averages(jobs)
    n = sum(1 for _, _, name in r.gantt if name == "*")
    print(f"{q:>3} {turn:>10.1f} {resp:>8.1f} {n:>8} {n / (n + work):>8.3f}"
          f" {1 / (q + 1):>7.3f} {load * (q + 1) / q:>11.2f}")
```

***Listing 10.8.** The print shop’s workload and the sweep over the quantum. code/bachelor-3/10-kernel-and-scheduling/listings/rr_quantum.py*

```
$ python rr_quantum.py
60 jobs, 1855 units of work, last arrival 2851, load 0.65
FCFS  turnaround   51.6  response  20.7
SJF   turnaround   47.8  response  16.9
  q turnaround response switches overhead s/(q+s) load(q+s)/q
  1      402.7     11.9     1628    0.467   0.500        1.30
  2      135.9      6.8      760    0.291   0.333        0.98
  3       78.9      4.9      384    0.172   0.250        0.87
  4       62.9      4.4      278    0.130   0.200        0.81
  5       48.5      3.4      166    0.082   0.167        0.78
  6       47.5      3.7      147    0.073   0.143        0.76
  7       47.0      4.0      134    0.067   0.125        0.74
  8       46.5      4.1      125    0.063   0.111        0.73
  9       44.9      4.4      108    0.055   0.100        0.72
 10       44.5      5.2      100    0.051   0.091        0.72
 11       44.0      5.2       98    0.050   0.083        0.71
 12       43.2      5.0       96    0.049   0.077        0.70
 13       43.7      5.3       95    0.049   0.071        0.70
 14       43.6      6.0       90    0.046   0.067        0.70
 15       43.6      6.3       87    0.045   0.062        0.69
 16       43.5      5.7       90    0.046   0.059        0.69
 17       42.5      6.0       84    0.043   0.056        0.69
 18       43.4      5.9       86    0.044   0.053        0.69
 19       44.8      6.9       88    0.045   0.050        0.68
 20       44.5      7.4       85    0.044   0.048        0.68
```

***Output 10.8.** Averages for each policy; for round robin, the number of switches, the fraction of the machine’s busy time spent switching, the model $s/(q + s)$, and the load once switching is paid for.*

![Round robin on the print shop’s jobs, on a logarithmic scale. Below q = 3 the switches eat a quarter of the machine or more and the turnaround explodes; from q = 9 to 20 it is flat, below first come first served’s; the response time is least near q = 5 and grows, unevenly, beyond it.](https://one-course.com/images/onecourse/chapters/computer-science-5/b3-kernel-and-scheduling/fig-7a2c022f39b7.svg)

*Round robin on the print shop’s jobs, on a logarithmic scale. Below $q = 3$ the switches eat a quarter of the machine or more and the turnaround explodes; from $q = 9$ to 20 it is flat, below [first come first served](#def-b3-kernel-and-scheduling-policies)’s; the [response time](#def-b3-kernel-and-scheduling-metrics) is least near $q = 5$ and grows, unevenly, beyond it.*

**Part I — Without preemption.**

1. What is the load, the fraction of the time the machine would be busy without switching? Why must it stay below 1?
2. [First come first served](#def-b3-kernel-and-scheduling-policies) gives an average turnaround of 51.6 units. Why is the average [response time](#def-b3-kernel-and-scheduling-metrics) , 20.7, so large when most jobs are small?
3. Why does [shortest job first](#def-b3-kernel-and-scheduling-policies) improve both averages, and by how much?
4. Why is [shortest job first](#def-b3-kernel-and-scheduling-policies) not fair to the long jobs? Give the situation in which a long job waits longest.
5. Under [first come first served](#def-b3-kernel-and-scheduling-policies) , how many switches are there at most? What fraction of the busy time do they cost?
6. What does a customer with a 3-unit job care about: turnaround or response? And the shop?

**Part II — Round robin with a switch cost.**

7. If every turn uses a whole quantum, show that the fraction of busy time spent switching is $s/(q + s)$ .
8. Why is the measured overhead below $s/(q + s)$ for every $q \ge 2$ ?
9. With load $\rho$ and every turn using a whole quantum, show that the machine’s load once switches are paid for is $\rho (q + s)/q$ . For which $q$ is it below 1 here?
10. Explain the turnaround of 402.7 at $q = 1$ from the last column.
11. Why does round robin’s [response time](#def-b3-kernel-and-scheduling-metrics) grow with $q$ ? What does it tend to as $q$ grows?
12. What does round robin become when $q$ exceeds every burst?

**Part III — Measured.**

13. Read the quantum $q^*$ with the least average turnaround, and its value. By how much does it beat [first come first served](#def-b3-kernel-and-scheduling-policies) , and [shortest job first](#def-b3-kernel-and-scheduling-policies) ?
14. Over which range of $q$ is the turnaround within 3 % of its minimum?
15. Compare the overhead at $q = 2$ with the model, and explain the agreement.
16. At $q = 5$ , the overhead is 8.2 %, about half the model’s 16.7 %. How many switches would full quanta need, against the 166 measured, and why are there fewer?
17. Why is the [response time](#def-b3-kernel-and-scheduling-metrics) at $q = 1$ (11.9) larger than at $q = 5$ (3.4), when a shorter quantum should give a faster first turn?
18. Count the switches at $q = 20$ : why are they close to the number of turns [first come first served](#def-b3-kernel-and-scheduling-policies) would need?

**Part IV — Choosing the quantum.**

19. A rule of thumb sets the quantum so that most jobs finish within one. Which $q$ does it suggest here, and how does it do?
20. If the switch cost doubled to $s = 2$ , which quanta would make the machine overloaded?
21. What would change if the small jobs were interactive, needing a fast first response?
22. Why would a [multilevel feedback queue](#def-b3-kernel-and-scheduling-mlfq) suit this shop?
23. A long job of 120 units arrives at an empty shop at $q = 17$ . How many switches does it cause if nothing else arrives?
24. Sum up: what quantum do you choose, what does it cost in switching, and what does it gain over [first come first served](#def-b3-kernel-and-scheduling-policies) ?

**Solution of Problem 10.1.**

**1.** $1{,}855/2{,}851 \approx 0.65$. Above 1, work arrives faster than the machine can do it, and the queue grows without end.

**2.** A small job that arrives behind a long one waits for all of it: a few long jobs make everyone behind them wait, the *convoy* effect.

**3.** It lets the small jobs pass the long ones whenever both are waiting: turnaround 47.8 instead of 51.6 (7 % less), response 16.9 instead of 20.7.

**4.** A long job is passed by every small job that arrives while it waits; under a steady stream of small jobs it waits until the stream stops.

**5.** At most one per job after the first, 59: $59/(1{,}855 + 59) \approx 3.1~\%$ of the busy time.

**6.** The customer cares about turnaround, when the print is ready; response matters only to someone who watches the first page come out. The shop cares about the time lost switching, and about not starving anyone.

**7.** Each turn is $q$ units of work followed by $s$ of switching: $s/(q + s)$ of the time.

**8.** Many turns end early, because a job of 2 to 12 units finishes before its quantum is over, and a job alone in the shop runs on without any switch.

**9.** Work $\rho$ per unit of time needs $\rho(q + s)/q$ once each $q$ units cost $q + s$. Below 1 for $q > \rho s/(1 - \rho) = 0.65/0.35 \approx 1.9$: $q \ge 2$, where it is 0.98.

**10.** At $q = 1$ the load with switching is 1.30: the machine cannot keep up, the queue grows through the whole run, and every job waits in it.

**11.** Every job ahead of a new one may run a whole quantum first, so the first turn comes later as $q$ grows. As $q$ grows beyond every burst, it tends to [first come first served](#def-b3-kernel-and-scheduling-policies)’s 20.7.

**12.** [First come first served](#def-b3-kernel-and-scheduling-policies), with a switch at each change of job.

**13.** $q^* = 17$, with 42.5: 17.6 % below [first come first served](#def-b3-kernel-and-scheduling-policies)’s 51.6, 11 % below [shortest job first](#def-b3-kernel-and-scheduling-policies)’s 47.8.

**14.** Within 3 % means at most 43.8: from $q = 12$ to $q = 18$.

**15.** 0.291 against 0.333. At $q = 2$ the machine is nearly saturated, the queue is rarely empty and almost every job needs several quanta, so almost every turn is a full quantum followed by a switch, as the model assumes.

**16.** Full quanta would need $1{,}855/5 = 371$ turns, so about 371 switches; there are 166, because most small jobs finish in one or two turns that are not full, and a job alone in the shop needs no switch.

**17.** At $q = 1$ the shop is overloaded and the queue keeps growing: a new job waits behind a long queue even for one unit.

**18.** 85 switches, against 59 for [first come first served](#def-b3-kernel-and-scheduling-policies): with $q = 20$ every small job finishes in one turn, and only the long jobs, when others wait, are cut into several turns.

**19.** Small jobs are at most 12 units: $q = 12$, with 43.2, within 2 % of the best.

**20.** $\rho(q + 2)/q < 1$ needs $q > 2\rho/(1 - \rho) \approx 3.7$: quanta 1 to 3 would overload the shop.

**21.** A short quantum near 5 gives the best response, 3.4, for a turnaround of 48.5, still below [first come first served](#def-b3-kernel-and-scheduling-policies).

**22.** Small jobs would finish on the top level with a short quantum and respond at once; long jobs would sink to levels with long quanta and switch rarely, which is the best of both ends of the figure.

**23.** At most one, when it starts: when its quantum ends and nobody waits, it runs on without a switch.

**24.** A quantum of 12 to 17 units. The switches then cost about 4.5 % of the machine’s busy time (the measured overhead, well below the model’s $s/(q + s)$ of 5.6 to 7.7 %), and the average turnaround falls to 42.5–43.7, about 17 % below [first come first served](#def-b3-kernel-and-scheduling-policies), with an average response of 5 to 6.3 units instead of 20.7. Below $q = 3$ the switching overloads the shop; above 18 the turnaround drifts back towards [first come first served](#def-b3-kernel-and-scheduling-policies).
