本书暂未推出简体中文版。现有版本:English。
High School Computer Science · 10–12 年级
31Processes and Scheduling
A laptop with four processor cores runs some three hundred programs “at the same time”: the editor, the browser and its tabs, the music player, and many small programs of the operating system that nobody started by hand. Four cores can run four instructions at once, not three hundred. The rest is an illusion that the operating system maintains by switching from one program to the next many times a second.
This chapter looks at a running program, a process, from the operating system’s side: how it is created, the states it passes through, and how the system chooses which one runs. Sharing the processor raises two new kinds of bug, a lost update and a deadlock, which appear only when programs run together; both are shown on small simulations where every possible order can be tried.
You already know
The kernel is the part of the operating system that manages the hardware and runs programs; programs ask it for services by system calls, and the shell starts commands (chapter 14). A state machine moves between states on events (chapter 10). A queue serves its elements first in, first out (chapter 24). A cycle in a directed graph is a path that comes back to its start (chapter 26).
31.1 Programs and processes
Definition 31.1 (Process)
A process is a program being run. It has its own memory (its code, its data, its stack), the values of the processor’s registers when it last ran, the files it has opened, and a number, its process identifier, given by the operating system.
One program can give several processes: two windows of the same editor are two processes running the same code with different data. A process creates another by a system call; the new one is its child. In Python, the module subprocess starts a child and waits for it.
"""A Python program starts another program, a child process, and waits for it."""
import subprocess
import sys
child = "import os; print('child: my parent is process', os.getppid() > 0); exit(3)"
result = subprocess.run([sys.executable, "-c", child], capture_output=True, text=True)
print("parent: the child printed:", result.stdout.strip())
print("parent: the child's exit status:", result.returncode)
result = subprocess.run(["ls", "no-such-file"], capture_output=True, text=True)
print("parent: ls exited with", result.returncode, "and wrote:", result.stderr.strip())
$ python spawn.py
parent: the child printed: child: my parent is process True
parent: the child's exit status: 3
parent: ls exited with 2 and wrote: ls: cannot access 'no-such-file': No such file or directory
The command ps lists processes. Below, a shell starts sleep 30 in the background with &, so that the shell does not wait for it; $! is the number of that last background process, and $$ the shell’s own. The option -p selects processes by number, and -o state=,comm= asks for two columns: the state and the command.
$ sleep 30 &
$ sleep 1
$ ps -o state=,comm= -p $!
S sleep
$ ps -o state=,comm= -p $$
S bash
S, asleep: sleep waits for its thirty seconds to pass, the shell for ps to finish.31.2 The states of a process
Definition 31.2 (Process states)
At each moment a process is in one of three states: running, if a processor core is executing it; ready, if it could run but waits for a core; blocked, if it waits for an event, such as the end of a disk read, a key press or a message from the network, and could not use a core if it had one.
The output of ps above uses letters for these states: R for running or ready, S for asleep, waiting for an event to complete.
31.3 The scheduler
Definition 31.3 (Interrupt)
An interrupt is a signal from a device to the processor that makes it stop the current program, at the end of the current instruction, and run a function of the kernel. A timer, the network card or the disk controller each sends interrupts; the kernel’s function decides what happens next.
A timer interrupts the processor at a regular pace, many times a second. Each time, the kernel can take the processor away from the running process and give it to another.
Definition 31.4 (Scheduler, quantum, round robin)
The scheduler is the part of the kernel that chooses which ready process runs next. A quantum is the longest time a process may run before it is interrupted and sent back to the ready queue. Round robin keeps the ready processes in a queue: it runs the first one for at most a quantum, then puts it back at the end of the queue if it is not finished. First come, first served runs each process to its end, in order of arrival.
Definition 31.5 (Context switch)
A context switch is the work of the kernel to stop one process and start another: save the registers of the first, choose the second, restore its registers and its memory map. While it happens, no process does useful work.
The simulator below follows these rules on a workload: a list of processes, each with its arrival time and the processor time it needs, its burst. Time is counted in units, the same for all. A process’s turnaround is its finish time minus its arrival; its waiting time is its turnaround minus its burst; its response time is the time from its arrival to its first run.
"""Two schedulers, simulated: first come first served, and round robin."""
from collections import deque
def fcfs(workload, switch=0):
"""workload: (name, arrival, burst) by arrival. Return slices (name, start, end)."""
time, slices = 0, []
for name, arrival, burst in workload:
if slices and time >= arrival:
time += switch # switching to the next process
time = max(time, arrival)
slices.append((name, time, time + burst))
time += burst
return slices
def round_robin(workload, quantum, switch=0):
left = {name: burst for name, _, burst in workload}
waiting = deque(workload) # not yet arrived, by arrival
ready, time, slices, last = deque(), 0, [], None
while waiting or ready:
while waiting and waiting[0][1] <= time:
ready.append(waiting.popleft()[0]) # arrivals join the end of the queue
if not ready:
time = waiting[0][1] # the processor is idle until then
continue
name = ready.popleft()
if last is not None and last != name:
time += switch # a context switch
run = min(quantum, left[name])
slices.append((name, time, time + run))
time += run
left[name] -= run
while waiting and waiting[0][1] <= time:
ready.append(waiting.popleft()[0])
if left[name] > 0:
ready.append(name) # back to the end of the queue
last = name
return slices
def times(workload, slices):
"""Turnaround (finish - arrival) and waiting (turnaround - burst) of each."""
finish = {name: end for name, _, end in slices}
return {name: (finish[name] - arrival, finish[name] - arrival - burst)
for name, arrival, burst in workload}
def gantt(slices):
"""One line of text: one letter per time unit, '.' when no process runs."""
line, time = "", 0
for name, start, end in slices:
line += "." * (start - time) # idle, or switching
line += name * (end - start)
time = end
return line
from scheduler import fcfs, gantt, round_robin, times
workload = [("A", 0, 5), ("B", 1, 3), ("C", 2, 8), ("D", 3, 2)] # name, arrival, burst
for title, slices in [("FCFS ", fcfs(workload)),
("RR, q = 2", round_robin(workload, 2)),
("RR, q = 4", round_robin(workload, 4))]:
t = times(workload, slices)
mean_turn = sum(a for a, _ in t.values()) / len(t)
mean_wait = sum(w for _, w in t.values()) / len(t)
first = {}
for name, start, _ in slices:
first.setdefault(name, start) # the first time each one runs
response = sum(first[n] - a for n, a, _ in workload) / len(workload)
print(f"{title} {gantt(slices)}")
print(f" turnaround {mean_turn:5.2f} waiting {mean_wait:5.2f}"
f" response {response:4.2f} {len(slices)} slices")
$ python fcfs_rr.py
FCFS AAAAABBBCCCCCCCCDD
turnaround 10.25 waiting 5.75 response 5.75 4 slices
RR, q = 2 AABBCCAADDBCCACCCC
turnaround 11.75 waiting 7.25 response 2.00 10 slices
RR, q = 4 AAAABBBCCCCDDACCCC
turnaround 11.50 waiting 7.00 response 4.00 6 slices
The choice of the quantum is a compromise. A short quantum gives each process a turn soon, which is what a person at a keyboard notices; but each switch costs time. A long quantum wastes little in switches, but round robin then behaves like first come, first served. The problem of the chapter measures this compromise.
31.4 Two processes and one variable
Processes that share data, such as two threads of a program updating the same counter, can be interrupted between any two instructions. The line counter += 1 is three instructions for the processor: load the counter into a register, add to the register, store the register back. The program below plays two such processes in every possible order.
"""Two processes each add 1 to a shared counter, in three steps: every interleaving."""
from itertools import combinations
def steps(name):
"""counter += 1, as the processor does it: load, add, store."""
return [(name, "load"), (name, "add"), (name, "store")]
def run(schedule):
counter, register = 0, {}
for name, action in schedule:
if action == "load":
register[name] = counter # copy the shared value
elif action == "add":
register[name] += 1 # change the private copy
else:
counter = register[name] # write the copy back
return counter
def interleavings(p, q):
"""Every order of the steps of p and q that keeps each one's own order."""
n = len(p) + len(q)
for places in combinations(range(n), len(p)): # where p's steps go
it_p, it_q = iter(p), iter(q)
yield [next(it_p) if k in places else next(it_q) for k in range(n)]
if __name__ == "__main__":
results = [run(s) for s in interleavings(steps("P"), steps("Q"))]
print(len(results), "interleavings:", results.count(2), "give 2,",
results.count(1), "give 1 (an update lost)")
bad = next(s for s in interleavings(steps("P"), steps("Q")) if run(s) == 1)
print("for instance:", ", ".join(f"{n} {a}" for n, a in bad))
$ python interleave.py
20 interleavings: 2 give 2, 18 give 1 (an update lost)
for instance: P load, P add, Q load, P store, Q add, Q store
Definition 31.6 (Race condition, critical section, mutual exclusion, lock)
A race condition is a bug whose effect depends on the order in which processes happen to run. A critical section is a part of a program that uses shared data and must not run in two processes at once. Mutual exclusion is the guarantee that at most one process is in a critical section at any time. A lock provides it: a process acquires the lock before the critical section and releases it after; a process that tries to acquire a lock already held waits until it is released.
"""The same two processes, with a lock around the three steps: every possible run."""
def program(name):
return [(name, a) for a in ["acquire", "load", "add", "store", "release"]]
def explore(p, q):
"""Final counter of every complete run; a step waits while the lock is taken."""
finals = []
def go(i, j, holder, counter, reg):
if i == len(p) and j == len(q):
finals.append(counter)
return
for who, prog, k in [("P", p, i), ("Q", q, j)]:
if k == len(prog):
continue
_, action = prog[k]
if action == "acquire" and holder is not None:
continue # blocked: the lock is taken
h, c, r = holder, counter, dict(reg)
if action == "acquire":
h = who
elif action == "release":
h = None
elif action == "load":
r[who] = c
elif action == "add":
r[who] += 1
else:
c = r[who]
go(i + (who == "P"), j + (who == "Q"), h, c, r)
go(0, 0, None, 0, {})
return finals
finals = explore(program("P"), program("Q"))
print(len(finals), "possible runs; final counter:", sorted(set(finals)))
$ python with_lock.py
2 possible runs; final counter: [2]
A real lock must itself be acquired without a race: two processes testing “is it free?” and then taking it would repeat the bug. Processors provide special instructions that test and set a memory cell in one indivisible step, and operating systems build locks on them.
31.5 Deadlock
Definition 31.7 (Deadlock)
A deadlock is a state in which each process of a group waits for a resource held by another process of the group, so that none of them can ever go on.
The simplest case needs two locks. P takes A, then B; Q takes B, then A. If each takes its first lock before the other takes its second, both wait for ever.
"""Two processes, two locks: every run, and the ones where both wait for ever."""
def explore(p, q):
"""Return the runs that end with both processes blocked."""
stuck = []
def go(i, j, owner, trace):
moves = []
for who, prog, k in [("P", p, i), ("Q", q, j)]:
if k < len(prog):
action, lock = prog[k]
if action == "take" and owner.get(lock) not in (None, who):
continue # held by the other one: wait
moves.append((who, action, lock))
if not moves:
if i < len(p) or j < len(q): # nobody can move, and work is left
wants = {"P": p[i][1], "Q": q[j][1]}
stuck.append((trace, {who: owner[wants[who]] for who in wants}))
return
for who, action, lock in moves:
o = dict(owner)
o[lock] = who if action == "take" else None
step = f"{who} {action}s {lock}"
go(i + (who == "P"), j + (who == "Q"), o, trace + [step])
go(0, 0, {}, [])
return stuck
def cycle(waits_for, start):
"""Follow 'who waits for whom' from start; return the cycle met, or None."""
path, who = [], start
while who is not None and who not in path:
path.append(who)
who = waits_for.get(who)
return path[path.index(who):] + [who] if who is not None else None
def run_pair(p_order, q_order):
p = [("take", x) for x in p_order] + [("free", x) for x in p_order]
q = [("take", x) for x in q_order] + [("free", x) for x in q_order]
return explore(p, q)
stuck = run_pair("AB", "BA")
print("P takes A then B, Q takes B then A:", len(stuck), "runs end in a deadlock")
trace, waits_for = stuck[0]
print(" for instance:", ", ".join(trace))
print(" wait-for graph:", waits_for, "cycle:", " -> ".join(cycle(waits_for, "P")))
print("both take A then B:", len(run_pair("AB", "AB")), "runs end in a deadlock")
$ python deadlock_sim.py
P takes A then B, Q takes B then A: 2 runs end in a deadlock
for instance: P takes A, Q takes B
wait-for graph: {'P': 'Q', 'Q': 'P'} cycle: P -> Q -> P
both take A then B: 0 runs end in a deadlock
A deadlock needs four conditions together: mutual exclusion (a resource is held by one process at a time), hold and wait (a process keeps what it holds while it waits for more), no preemption (a resource cannot be taken away from the process holding it), and circular wait (a cycle of processes, each waiting for the next). Breaking any one prevents deadlock. The usual remedy breaks the fourth: number the resources, and have every process take them in increasing order. A cycle would then need a process waiting for a resource numbered lower than one it holds, which the rule forbids; the last line of the output checks it on every run.
History — Coffman, Elphick and Shoshani, 1971
The four conditions were stated together by Edward G. Coffman, Michael Elphick and Arie Shoshani in “System deadlocks”, a survey published in 1971 in ACM Computing Surveys.
31.6 Exercises
Exercise 31.1 ★
Three processes arrive at time in the order X (burst ), Y (), Z (). Give the order and the slices of first come, first served.
Solution
Solution of Exercise 31.1.
In order of arrival: X from to , Y from to , Z from to . The Gantt line is XXXXYZZZ.
Exercise 31.2 ★
Compute the waiting time of each process of exercise 31.1, and the mean.
Solution
Solution of Exercise 31.2.
X waits , Y waits , Z waits : a mean of .
Exercise 31.3 ★
Write the Gantt line of round robin with a quantum of on X, Y, Z of exercise 31.1.
Solution
Solution of Exercise 31.3.
XYZXZXZX. Y is done after its first unit; Z after its third turn, at time ; X runs alone at the end.
Exercise 31.4 ★
How many context switches does round robin with make on the workload of the chapter? And with ?
Solution
Solution of Exercise 31.4.
A switch happens each time the next slice belongs to another process. With the slices are A, B, C, A, D, B, C, A, C, C: switches, since C’s last two slices follow each other. With the slices A, B, C, D, A, C make .
Exercise 31.5 ★
Write turnaround(workload, slices), which returns the turnaround of each process as a dictionary.
Solution
Solution of Exercise 31.5.
def turnaround(workload, slices):
finish = {name: end for name, _, end in slices}
return {name: finish[name] - arrival for name, arrival, _ in workload}
The dictionary keeps the last slice of each name, which is where the process finishes.
Exercise 31.6 ★★
A round robin forgets to put an unfinished process back in the queue. What happens on the workload of the chapter with ?
Solution
Solution of Exercise 31.6.
Each process runs once, for at most units: A from to , B from to , C from to , D from to . Then the queue is empty and the simulation stops. Only D, whose burst is , has finished; A, B and C are left with , and units, and will never run again. The tests check these remainders.
Exercise 31.7 ★★
How many interleavings do two processes of steps each have? Of and steps? Explain the count.
Solution
Solution of Exercise 31.7.
. An interleaving of steps is fixed by choosing which of the places hold P’s steps, in their own order; the other places hold Q’s. There are such choices. For and steps: , which is how interleavings enumerates them, with combinations.
Exercise 31.8 ★★
Write sjf(workload), shortest job first: when the processor is free, it runs to its end the ready process with the smallest burst. Apply it to the workload of the chapter.
Solution
Solution of Exercise 31.8.
def sjf(workload):
pending, time, slices = sorted(workload, key=lambda w: w[1]), 0, []
while pending:
arrived = [w for w in pending if w[1] <= time]
if not arrived:
time = pending[0][1]
continue
job = min(arrived, key=lambda w: (w[2], w[1]))
pending.remove(job)
slices.append((job[0], time, time + job[2]))
time += job[2]
return slices
On the chapter’s workload, A is alone at time and runs to ; then D (), B () and C (): D from to , B to , C to . Turnarounds , , , : a mean of , against for first come, first served.
Exercise 31.9 ★★
A function acquires a lock, and returns early, without releasing it, when the value it reads is negative. What happens to the other processes that use the lock?
Solution
Solution of Exercise 31.9.
The lock stays held by a process that has left the critical section. Every other process that tries to acquire it waits for ever, and so does the same process on its next call. The fix releases the lock on every path: in Python, with lock: around the critical section, which releases it however the block is left, even by an exception.
Exercise 31.10 ★★
Give the final counter for the order: P load, Q load, Q add, Q store, P add, P store. Is an update lost?
Solution
Solution of Exercise 31.10.
P loads ; Q loads , adds, stores ; P adds to its own copy, , and stores . The final counter is : Q’s update is lost, overwritten by P’s.
Exercise 31.11 ★★
Two designs. In the first, processes never use the printer: they hand whole documents to a printer server, which prints them one after the other. In the second, a process asks for all the resources it will need in one request, granted all at once or not at all, before it starts. Which of the four conditions of deadlock does each design rule out?
Solution
Solution of Exercise 31.11.
The first design rules out mutual exclusion as far as the processes are concerned: none of them ever holds the printer, only the server does, so no process can wait for another to give it back. The second rules out hold and wait: a process that waits holds nothing, and a process that holds its resources never waits for more.
Exercise 31.12 ★★★
Prove that with the lock, no run of with_lock.py loses an update, whatever the order of the steps.
Solution
Solution of Exercise 31.12.
Between its acquire and its release, a process holds the lock, and the other cannot pass its own acquire. So the three steps of one process are never interleaved with those of the other: one process, say the first to acquire, does load, add, store, and releases; only then can the second load. Two cases, P first or Q first, and in both the second process loads the value stored by the first and stores . Steps outside the lock are only acquire and release, which do not touch the counter. The program finds the same: exactly runs, both ending at .
Exercise 31.13 ★★★
Write has_cycle(waits_for), which detects a deadlock in a wait-for graph given as a dictionary from each process to the list of processes it waits for.
Solution
Solution of Exercise 31.13.
A depth-first search that marks the vertices still being explored: meeting one of them again closes a cycle.
def has_cycle(waits_for):
state = {}
def visit(v):
state[v] = "open"
for w in waits_for.get(v, []):
if state.get(w) == "open" or (w not in state and visit(w)):
return True
state[v] = "done"
return False
return any(v not in state and visit(v) for v in list(waits_for))
A vertex marked done has no cycle below it, so it is never explored twice. The tests try a cycle of three processes and a chain without one.
Exercise 31.14 ★★★
Four processes arrive at time with bursts , , , . Compute the mean waiting time of first come, first served and of shortest job first. Show that, when all processes arrive together, shortest job first gives the smallest mean waiting time of all orders.
Solution
Solution of Exercise 31.14.
First come, first served: waits , , , , a mean of . Shortest job first runs , , , : waits , , , , a mean of .
When all arrive at , the process in place (from to ) makes the processes after it wait for its burst, so the total waiting time is the sum of each burst times the number of processes after it. Take any order in which a longer burst comes just before a shorter one . Swapping the two changes nothing for the others, and changes the total by : the swap improves the order. So an order with the smallest total has no such pair: its bursts are increasing, which is shortest job first. The tests compare it with all orders.
Exercise 31.15 ★★★
Five philosophers sit at a round table, with a fork between each two. To eat, a philosopher takes the fork on the left, then the one on the right. Show that a deadlock can happen, and that taking the lower-numbered fork first prevents it.
Solution
Solution of Exercise 31.15.
Number the philosophers and forks to ; philosopher uses forks and (fork for the last). If all five take their left fork at once, every fork is held and each waits for the right one, held by a neighbour: a cycle of five, a deadlock. With the rule “lower-numbered fork first”, philosophers to still start on the left, but philosopher starts with fork . A cycle would need each philosopher to hold one fork and wait for a higher-numbered one; philosopher would hold fork and wait for fork , but then philosopher holds nothing, and the cycle breaks. The function philosophers tries every reachable state and confirms: a deadlock without the rule, none with it.
31.7 Problem: Choosing the Quantum
Problem 31.1
Weekend problem — how long should a turn last?
Five processes share one core: A, a long computation, arrives first; four short ones follow. Every context switch costs one unit of time. The program tries round robin with every quantum from to .
"""Choosing the quantum: mean turnaround of round robin, with a context switch of 1."""
from scheduler import fcfs, round_robin, times
workload = [("A", 0, 20), ("B", 1, 3), ("C", 2, 6), ("D", 3, 2), ("E", 5, 4)]
SWITCH = 1
def mean_turnaround(slices):
t = times(workload, slices)
return sum(turn for turn, _ in t.values()) / len(t)
def switches(slices):
return sum(a[0] != b[0] for a, b in zip(slices, slices[1:]))
slices = fcfs(workload, SWITCH)
print(f"FCFS : mean turnaround {mean_turnaround(slices):5.1f}, "
f"{switches(slices):2} switches, all done at {slices[-1][2]}")
best = None
for q in range(1, 13):
slices = round_robin(workload, q, SWITCH)
m = mean_turnaround(slices)
print(f"q = {q:2} : mean turnaround {m:5.1f}, {switches(slices):2} switches,"
f" all done at {slices[-1][2]}")
if best is None or m < best[1]:
best = (q, m)
print("best quantum:", best[0], "with a mean turnaround of", best[1])
$ python quantum.py
FCFS : mean turnaround 27.4, 4 switches, all done at 39
q = 1 : mean turnaround 32.8, 22 switches, all done at 57
q = 2 : mean turnaround 25.4, 11 switches, all done at 46
q = 3 : mean turnaround 22.4, 9 switches, all done at 44
q = 4 : mean turnaround 22.0, 7 switches, all done at 42
q = 5 : mean turnaround 22.4, 7 switches, all done at 42
q = 6 : mean turnaround 20.2, 5 switches, all done at 40
q = 7 : mean turnaround 21.0, 5 switches, all done at 40
q = 8 : mean turnaround 21.8, 5 switches, all done at 40
q = 9 : mean turnaround 22.6, 5 switches, all done at 40
q = 10 : mean turnaround 23.4, 5 switches, all done at 40
q = 11 : mean turnaround 24.2, 5 switches, all done at 40
q = 12 : mean turnaround 25.0, 5 switches, all done at 40
best quantum: 6 with a mean turnaround of 20.2
Part I — The workload.
- How much processor time does the workload need in all?
- Why can no schedule finish everything before time ?
- With first come, first served, in which order do the processes run? Give the slices, with the switches.
- Compute the turnaround of each process under first come, first served, and check the mean printed.
Part II — Short and long quanta.
- Why is round robin with worse than first come, first served here?
- Count the time lost in switches for , and check it against the time when everything is done.
- Why is the result the same for every ? Which schedule is it?
- Why do and first come, first served differ, although A runs first in both?
Part III — The best quantum.
- Which quantum gives the smallest mean turnaround? By how much does it beat first come, first served?
- With , write the slices, and find when each process finishes.
- Explain why suits this workload: compare it with the bursts of the short processes.
- Why does the mean grow again for from to ?
- The mean does not change steadily with : is worse than . Compare the finishing time of each process for the two quanta, and explain.
Part IV — Other measures.
- Compute the response time of B under first come, first served and under .
- A person typing in an editor cares about the response time; a person waiting for a report, about the turnaround. Which quantum would each prefer here?
- If a switch cost nothing, the program gives a mean turnaround of for , and for and . Why does improve so much, and why is it still not the best?
- Shortest job first is not round robin. Would it beat the best quantum on this workload? Why can a real scheduler not use it directly?
- Suppose a quantum of milliseconds and a switch costing microseconds. What fraction of the processor time goes to switches when every quantum is used in full? Compare with here.
- Why do real systems also change the quantum, or the order, for processes that often block?
- State the result: the best quantum for this workload and switch cost, its mean turnaround, and that of first come, first served.
Solution
Solution of Problem 31.1.
1. units.
2. The core does one unit of work per unit of time, and the work starts at , so at least ; five processes also need at least four switches, so at least .
3. By arrival, with a switch between each: A from to , B –, C –, D –, E –.
4. , , , , : , the value printed.
5. Each unit of work is followed by a switch, so units are lost. B, D and E finish sooner than under first come, first served (turnarounds , , against , , ), but C, sharing the core one unit at a time, takes instead of , and A instead of . The total grows by units, the mean by .
6. switches of unit, and , the time printed: the core is never idle.
7. With , every process finishes in its first turn, so nobody returns to the queue: the processes run once each, in order of arrival, which is first come, first served. The tests check to .
8. With , A is interrupted at and goes behind B, C, D and E, who all finish in their first turn; A comes back for its last units. The short processes finish units sooner; the extra switch makes everything end at .
9. , with : less than first come, first served.
10. A –, B –, C –, D –, E –, then A alone from to . B, C, D and E finish at , , , ; A at .
11. is the longest burst of the short processes (, , , ): each of them finishes in one turn, while A, the long one, is interrupted once and goes to the back.
12. Every short process already finishes in one turn, so a longer quantum only lengthens A’s first slice: B, C, D and E each finish one unit later per unit of quantum. The total grows by , the mean by , as printed.
13. Finishing times for : A , B , C , D , E ; for : A , B , C , D , E . A’s first slice is one unit longer, which delays B by ; C needs a second turn in both cases, and everything before it is longer, so C and D lose . E gains : it arrives at , which with is exactly when A’s slice ends, so E joins the queue before A; with , A is back in the queue at , ahead of E. In all units, so the mean grows by .
14. First come, first served: B arrives at and starts at , a response time of . With : it starts at , a response of .
15. The typist wants short response times, so a short quantum: with every process starts within a few units. The person waiting for a report wants the short turnarounds of .
16. Without switches, the lost units disappear, and round robin with shares the core finely, which lets the short processes finish early. It is still not best: the four short ones are slowed down by sharing with each other, a little more than with or , where each takes longer turns.
17. No: with the same switch cost of , shortest job first gives ( if switches were free). A is alone at time and, once started, runs to its end; the short processes all wait units. Round robin interrupts A, which shortest job first never does. A real scheduler cannot apply it as written because it does not know the bursts in advance: they depend on what the programs do.
18. of the time. Here, with and a switch of , up to , about : the toy cost is more than a hundred times heavier.
19. A process that blocks often, waiting for a key or the network, uses little of its quantum, and is ready again as soon as its event comes. Serving it first keeps its response short, and costs the long computations little, since it soon gives the core back.
20. For five processes, one of units and four of to , with a switch costing one unit, round robin with a quantum of gives the smallest mean turnaround, units, against for first come, first served and for a quantum of .