Este libro aún no está disponible en Español. Ediciones: English.
University Computer Science — Year 3 · Grado — Año 3
10The 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 and back out, how the 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 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 a call from the file system to a disk driver is a function call; in a microkernel it is two messages, each crossing into the kernel and out. In exchange, a faulty driver in a microkernel crashes one process, which can be restarted, where in a monolithic 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’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, 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 set.
On RISC-V, a trap 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; the processor then jumps to the address configured in mtvec. The instruction mret returns to the address in mepc. The machine timer interrupt becomes pending when the free-running counter mtime reaches the value of mtimecmp, which the kernel writes to choose the next tick.
ecall.Definition 10.3 (Preemption, context switch, process control block)
Preemption is the 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’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 gets control back at every tick, whatever the program does. rv has no timer, but a kernel written in Python around it can count the instructions and take control every 50 (Listing 10.1). The two programs it runs in turn are loops that never give the processor up (two_loops.S).
"""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")
rv: one process control block per program, a timer every 50 instructions, and a context 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
10.3 The context switch
The kernel’s switch, as Listing 10.1 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, called by the kernel’s own code: the trap entry saves the interrupted program’s registers on the kernel stack of that process, and the switch then only has to move from one 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 runs two coroutines, each on its own stack and each counting in s1; Listing 10.3 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.
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
s1. code/bachelor-3/10-kernel-and-scheduling/listings/switch.S# 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
ra and sp of one context, load the other’s, return into it. code/bachelor-3/10-kernel-and-scheduling/listings/switch.Sctx_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
Of the 371 instructions of the run, 232 are in the 8 switches. A real 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 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). POSIX marked these functions obsolescent in 2004 and later removed them, advising threads instead; the GNU C library still provides them.
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;
}
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
10.4 Scheduling policies
Definition 10.4 (Turnaround, waiting and response time)
For a job that arrives at time , needs units of processor time (its burst), first runs at time and finishes at time : its turnaround time is , its waiting time , the time it spent ready but not running, and its response time .
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 , the quantum, then puts it at the back of the queue.
sched.py simulates them (Listing 10.5): 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.
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
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)
job[start,end).Shortest remaining time first has the best averages, and round robin the worst turnaround but a response time close to the best. A policy is a choice of what to optimise. For waiting time, with all jobs present at once, shortest job first 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 over all orders.
Proof. In the order , the -th job waits , so the total waiting time is : the job in position delays the jobs after it. Take an order in which two neighbours are out of order, . Swapping them changes the total by . 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 is the preemptive counterpart, and Output 10.4 shows it ahead. Both need the bursts in advance, which a 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). Round robin cannot starve anyone, and bounds the response time.
Theorem 10.7 (Round robin’s response time)
With jobs ready at time 0, quantum and no switching cost, every job first runs by time .
The proof is exercise 10.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). 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.
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
$ 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
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.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
$ 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
Theorem 10.10 (Stride scheduling is nearly exact)
Let clients hold tickets, , with exact strides and initial passes . After quanta, client has received quanta with
In particular the error is less than one quantum for two clients, and less than for any number.
The proof is exercise 10.10. The lottery’s error after quanta grows like : 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 releases a job every units, needing 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 , the fraction of the processor the tasks need. Rate-monotonic scheduling meets every deadline if for tasks, a bound that decreases towards ; earliest deadline first meets every deadline whenever , which no policy can improve on. Exercise 10.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 in 1994.
10.5 Exercises
Exercise 10.1 ★
Draw the round-robin timeline with for P (arrives at 0, burst 5), Q (1, 3) and R (2, 1). When does each job finish?
Solution
Solution of Exercise 10.1.
P runs ; Q arrived at 1 and R at 2, both before P’s turn ends, so the queue is Q, R, P. Q runs , R and finishes, P , Q and finishes, P 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 under first come first served in that order, and under shortest job first.
Solution
Solution of Exercise 10.2.
In the given order the waits are 0, 6, 8 and 16: average 7.5. Shortest job first 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 by a trap, 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
Solution of Exercise 10.3.
ecall: a trap, an exception requested by the program. Integer division by zero: no trap at all; RISC-V defines its result, for the quotient. A load from address 0: a trap, an exception (an access fault). The timer reaching mtimecmp: a trap, an interrupt. A key pressed: an interrupt, from the keyboard’s controller. An illegal instruction: an exception. A ret: an ordinary jump, no trap.
Exercise 10.4 ★
In switch.S, main switches to ctx_b instead of ctx_a. Predict the output.
Solution
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
s1.Solution
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
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 under first come first served to that under shortest job first, for jobs all present at time 0, can be as large as you like.
Solution
Solution of Exercise 10.7.
Take one job of burst first and jobs of burst 1. First come first served makes each short job wait at least : total at least . Shortest job first runs the short ones first: total . The ratio is at least , as large as you like for a fixed when grows.
Exercise 10.8 ★★
Prove Theorem 10.7.
Solution
Solution of Exercise 10.8.
At time 0 the queue holds the jobs. A job runs at most units per turn, then goes to the back, and nothing arrives. So the -th job in the queue starts after the jobs before it have had one turn each, each of at most units: it first runs by . test_round_robin_response_bound checks it on 200 random sets.
Exercise 10.9 ★★
From Listing 10.3, count the instructions one switch executes, including those that prepare and make the call, and check the total against Output 10.2.
Solution
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 of the 371 instructions in the switch itself, and loads, all the loads of the run (test_switch_output_and_cost).
Exercise 10.10 ★★★
Prove Theorem 10.10. (Show first that the passes always lie within one stride of the least pass.) Check the bound against Output 10.6.
Solution
Solution of Exercise 10.10.
Client ’s pass after runs is . Let 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 has run, its pass before its last run, , was the least pass at that time, so ; if it has not run, . Hence , that is with and . Summing, with , so and
Since , this is at least (if it is ). Since , it is at most . For two clients the upper bound is . In Output 10.6 the bounds are , and 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 run under rate-monotonic scheduling. Prove that every deadline is met when .
Solution
Solution of Exercise 10.11.
Task 1 has the higher priority and is never delayed; it meets its deadlines if . Task 2’s job released at 0 (the worst case, released with task 1) is delayed only by task 1. Let . If , the last job of task 1 before finishes before , and task 2 needs . Otherwise it needs . In each case take as large as allowed and minimise over : is linear in on each side, so its minimum is at , where with . This is least for , and then is minimised at , giving . Any set with a smaller utilisation therefore meets all deadlines.
Exercise 10.12 ★★★
Build a workload in which shortest remaining time first 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, ?
Solution
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 at , as late as you like. With aging, , every 2 units waited take one unit off its key. At time 35 it has waited 34 units and its key is , 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 unit. Output 10.8 runs first come first served, shortest job first, and round robin for every quantum from 1 to 20; the figure after it plots the averages.
"""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}")
$ 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
Part I — Without preemption.
- What is the load, the fraction of the time the machine would be busy without switching? Why must it stay below 1?
- First come first served gives an average turnaround of 51.6 units. Why is the average response time, 20.7, so large when most jobs are small?
- Why does shortest job first improve both averages, and by how much?
- Why is shortest job first not fair to the long jobs? Give the situation in which a long job waits longest.
- Under first come first served, how many switches are there at most? What fraction of the busy time do they cost?
- 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.
- If every turn uses a whole quantum, show that the fraction of busy time spent switching is .
- Why is the measured overhead below for every ?
- With load and every turn using a whole quantum, show that the machine’s load once switches are paid for is . For which is it below 1 here?
- Explain the turnaround of 402.7 at from the last column.
- Why does round robin’s response time grow with ? What does it tend to as grows?
- What does round robin become when exceeds every burst?
Part III — Measured.
- Read the quantum with the least average turnaround, and its value. By how much does it beat first come first served, and shortest job first?
- Over which range of is the turnaround within 3 % of its minimum?
- Compare the overhead at with the model, and explain the agreement.
- At , 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?
- Why is the response time at (11.9) larger than at (3.4), when a shorter quantum should give a faster first turn?
- Count the switches at : why are they close to the number of turns first come first served would need?
Part IV — Choosing the quantum.
- A rule of thumb sets the quantum so that most jobs finish within one. Which does it suggest here, and how does it do?
- If the switch cost doubled to , which quanta would make the machine overloaded?
- What would change if the small jobs were interactive, needing a fast first response?
- Why would a multilevel feedback queue suit this shop?
- A long job of 120 units arrives at an empty shop at . How many switches does it cause if nothing else arrives?
- Sum up: what quantum do you choose, what does it cost in switching, and what does it gain over first come first served?
Solution
Solution of Problem 10.1.
1. . 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: 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 units of work followed by of switching: 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 per unit of time needs once each units cost . Below 1 for : , where it is 0.98.
10. At 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 grows. As grows beyond every burst, it tends to first come first served’s 20.7.
12. First come first served, with a switch at each change of job.
13. , with 42.5: 17.6 % below first come first served’s 51.6, 11 % below shortest job first’s 47.8.
14. Within 3 % means at most 43.8: from to .
15. 0.291 against 0.333. At 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 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 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: with 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: , with 43.2, within 2 % of the best.
20. needs : 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.
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 of 5.6 to 7.7 %), and the average turnaround falls to 42.5–43.7, about 17 % below first come first served, with an average response of 5 to 6.3 units instead of 20.7. Below the switching overloads the shop; above 18 the turnaround drifts back towards first come first served.
Términos definidos en este capítulo
- Fair-share scheduling: lottery and stride
- Interrupt, trap, hardware exception, interrupt vector, timer interrupt
- Kernel, monolithic kernel, microkernel
- Multilevel feedback queue
- Preemption, context switch, process control block
- Real-time scheduling, deadline, rate-monotonic, earliest deadline first
- Scheduling policies
- Turnaround, waiting and response time