计算机科学 · 第 2 册 · 10–12 年级

High School Computer Science

本书暂未推出简体中文版。现有版本: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())
Listing 31.1. A parent process starts two children. code/grade-12/10-processes-and-scheduling/listings/spawn.py
$ 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
Output 31.1. Each child ends with an exit status: 00 means success, anything else a failure that the parent can test.

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
Output 31.2. Both processes are in state 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 states of a process as a state machine. Only the scheduler moves a process into running; a blocked process always goes back through ready, even when its event is over.
The states of a process as a state machine. Only the scheduler moves a process into running; a blocked process always goes back through ready, even when its event is over.

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
Listing 31.2. First come, first served and round robin, simulated. code/grade-12/10-processes-and-scheduling/listings/scheduler.py
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
Listing 31.3. The times of each process, and a Gantt line of text. code/grade-12/10-processes-and-scheduling/listings/scheduler.py
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")
Listing 31.4. One workload, three schedules. code/grade-12/10-processes-and-scheduling/listings/fcfs_rr.py
$ 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
Output 31.3. Each letter is one unit of processor time given to that process. Round robin starts every process sooner, at the price of a longer turnaround.
Round robin with a quantum of 2 on the workload of the listing. A, B, C and D arrive at times 0 to 3. Each process runs at most two units, then goes to the end of the queue; B needs a third unit at time 10, A its fifth at time 13; C, the longest, finishes last at 18.
Round robin with a quantum of 22 on the workload of the listing. A, B, C and D arrive at times 00 to 33. Each process runs at most two units, then goes to the end of the queue; B needs a third unit at time 1010, A its fifth at time 1313; C, the longest, finishes last at 1818.

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 11 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))
Listing 31.5. Every interleaving of two three-step updates. code/grade-12/10-processes-and-scheduling/listings/interleave.py
$ 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
Output 31.4. Only two orders of the twenty give the right answer.
The interleaving printed above. Q loads the counter before P has stored its result, so both start from 0; P stores 1, then Q stores 1 over it. One of the two additions is lost.
The interleaving printed above. Q loads the counter before P has stored its result, so both start from 00; P stores 11, then Q stores 11 over it. One of the two additions is lost.

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)))
Listing 31.6. The two updates inside a lock, with every possible run. code/grade-12/10-processes-and-scheduling/listings/with_lock.py
$ python with_lock.py
2 possible runs; final counter: [2]
Output 31.5. Whoever acquires the lock first does its three steps alone: the counter is always 22.

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
Listing 31.7. Every run of two processes taking two locks. code/grade-12/10-processes-and-scheduling/listings/deadlock_sim.py
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")
Listing 31.8. The cycle of the wait-for graph, and the two orders of taking the locks. code/grade-12/10-processes-and-scheduling/listings/deadlock_sim.py
$ 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
Output 31.6. Opposite orders can deadlock; the same order never does.
The resource-allocation graph of the deadlock. Processes are circles, locks squares; an arrow from a lock to a process means “held by”, from a process to a lock “waits for”. The four arrows form a cycle. Leaving out the locks gives the wait-for graph of the output: P waits for Q, Q waits for P.
The resource-allocation graph of the deadlock. Processes are circles, locks squares; an arrow from a lock to a process means “held by”, from a process to a lock “waits for”. The four arrows form a cycle. Leaving out the locks gives the wait-for graph of the output: P waits for Q, Q waits for P.

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 00 in the order X (burst 44), Y (11), Z (33). Give the order and the slices of first come, first served.

Solution

Solution of Exercise 31.1.

In order of arrival: X from 00 to 44, Y from 44 to 55, Z from 55 to 88. 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 00, Y waits 44, Z waits 55: a mean of 9/3=39/3 = 3.

Exercise 31.3 ★

Write the Gantt line of round robin with a quantum of 11 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 77; X runs alone at the end.

Exercise 31.4 ★

How many context switches does round robin with q=2q = 2 make on the workload of the chapter? And with q=4q = 4?

Solution

Solution of Exercise 31.4.

A switch happens each time the next slice belongs to another process. With q=2q = 2 the 1010 slices are A, B, C, A, D, B, C, A, C, C: 88 switches, since C’s last two slices follow each other. With q=4q = 4 the 66 slices A, B, C, D, A, C make 55.

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 q=2q = 2?

Solution

Solution of Exercise 31.6.

Each process runs once, for at most 22 units: A from 00 to 22, B from 22 to 44, C from 44 to 66, D from 66 to 88. Then the queue is empty and the simulation stops. Only D, whose burst is 22, has finished; A, B and C are left with 33, 11 and 66 units, and will never run again. The tests check these remainders.

Exercise 31.7 ★★

How many interleavings do two processes of 33 steps each have? Of aa and bb steps? Explain the count.

Solution

Solution of Exercise 31.7.

2020. An interleaving of 66 steps is fixed by choosing which 33 of the 66 places hold P’s steps, in their own order; the other places hold Q’s. There are (63)=20\binom{6}{3} = 20 such choices. For aa and bb steps: (a+ba)\binom{a+b}{a}, 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 00 and runs to 55; then D (22), B (33) and C (88): D from 55 to 77, B to 1010, C to 1818. Turnarounds 55, 99, 1616, 44: a mean of 8.58.5, against 10.2510.25 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 00; Q loads 00, adds, stores 11; P adds to its own copy, 11, and stores 11. The final counter is 11: 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 11 stored by the first and stores 22. Steps outside the lock are only acquire and release, which do not touch the counter. The program finds the same: exactly 22 runs, both ending at 22.

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 00 with bursts 66, 88, 33, 22. 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 00, 66, 1414, 1717, a mean of 37/4=9.2537/4 = 9.25. Shortest job first runs 22, 33, 66, 88: waits 00, 22, 55, 1111, a mean of 18/4=4.518/4 = 4.5.

When all arrive at 00, the process in place kk (from 11 to nn) makes the n−kn - k 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 bb comes just before a shorter one c<bc < b. Swapping the two changes nothing for the others, and changes the total by c−b<0c - b < 0: 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 2424 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 00 to 44; philosopher kk uses forks kk and k+1k + 1 (fork 00 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 00 to 33 still start on the left, but philosopher 44 starts with fork 00. A cycle would need each philosopher to hold one fork and wait for a higher-numbered one; philosopher 44 would hold fork 00 and wait for fork 44, but then philosopher 00 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 11 to 1212.

"""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])
Listing 31.9. Round robin on one workload, for every quantum. code/grade-12/10-processes-and-scheduling/listings/quantum.py
$ 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
Output 31.7. Mean turnaround, number of switches, and the time when everything is done.

Part I — The workload.

  1. How much processor time does the workload need in all?
  2. Why can no schedule finish everything before time 3535?
  3. With first come, first served, in which order do the processes run? Give the slices, with the switches.
  4. Compute the turnaround of each process under first come, first served, and check the mean printed.

Part II — Short and long quanta.

  1. Why is round robin with q=1q = 1 worse than first come, first served here?
  2. Count the time lost in switches for q=1q = 1, and check it against the time when everything is done.
  3. Why is the result the same for every q≥20q \ge 20? Which schedule is it?
  4. Why do q=12q = 12 and first come, first served differ, although A runs first in both?

Part III — The best quantum.

  1. Which quantum gives the smallest mean turnaround? By how much does it beat first come, first served?
  2. With q=6q = 6, write the slices, and find when each process finishes.
  3. Explain why q=6q = 6 suits this workload: compare it with the bursts of the short processes.
  4. Why does the mean grow again for qq from 77 to 1212?
  5. The mean does not change steadily with qq: q=5q = 5 is worse than q=4q = 4. Compare the finishing time of each process for the two quanta, and explain.

Part IV — Other measures.

  1. Compute the response time of B under first come, first served and under q=6q = 6.
  2. 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?
  3. If a switch cost nothing, the program gives a mean turnaround of 17.417.4 for q=1q = 1, and 17.017.0 for q=2q = 2 and q=3q = 3. Why does q=1q = 1 improve so much, and why is it still not the best?
  4. 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?
  5. Suppose a quantum of 44 milliseconds and a switch costing 44 microseconds. What fraction of the processor time goes to switches when every quantum is used in full? Compare with q=6q = 6 here.
  6. Why do real systems also change the quantum, or the order, for processes that often block?
  7. 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. 20+3+6+2+4=3520 + 3 + 6 + 2 + 4 = 35 units.

2. The core does one unit of work per unit of time, and the work starts at 00, so at least 3535; five processes also need at least four switches, so at least 3939.

3. By arrival, with a switch between each: A from 00 to 2020, B 2121–2424, C 2525–3131, D 3232–3434, E 3535–3939.

4. 2020, 2323, 2929, 3131, 3434: 137/5=27.4137 / 5 = 27.4, the value printed.

5. Each unit of work is followed by a switch, so 2222 units are lost. B, D and E finish sooner than under first come, first served (turnarounds 2020, 1616, 3030 against 2323, 3131, 3434), but C, sharing the core one unit at a time, takes 4141 instead of 2929, and A 5757 instead of 2020. The total grows by 2727 units, the mean by 5.45.4.

6. 2222 switches of 11 unit, and 35+22=5735 + 22 = 57, the time printed: the core is never idle.

7. With q≥20q \ge 20, 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 q=20q = 20 to 2929.

8. With q=12q = 12, A is interrupted at 1212 and goes behind B, C, D and E, who all finish in their first turn; A comes back for its last 88 units. The short processes finish 88 units sooner; the extra switch makes everything end at 4040.

9. q=6q = 6, with 20.220.2: 7.27.2 less than first come, first served.

10. A 00–66, B 77–1010, C 1111–1717, D 1818–2020, E 2121–2525, then A alone from 2626 to 4040. B, C, D and E finish at 1010, 1717, 2020, 2525; A at 4040.

11. 66 is the longest burst of the short processes (33, 66, 22, 44): 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 44, the mean by 0.80.8, as printed.

13. Finishing times for q=4q = 4: A 4242, B 88, C 2929, D 1616, E 2626; for q=5q = 5: A 4242, B 99, C 3131, D 1818, E 2323. A’s first slice is one unit longer, which delays B by 11; C needs a second turn in both cases, and everything before it is longer, so C and D lose 22. E gains 33: it arrives at 55, which with q=5q = 5 is exactly when A’s slice ends, so E joins the queue before A; with q=4q = 4, A is back in the queue at 44, ahead of E. In all +1+2+2−3=+2+1 + 2 + 2 - 3 = +2 units, so the mean grows by 0.40.4.

14. First come, first served: B arrives at 11 and starts at 2121, a response time of 2020. With q=6q = 6: it starts at 77, a response of 66.

15. The typist wants short response times, so a short quantum: with q=1q = 1 every process starts within a few units. The person waiting for a report wants the short turnarounds of q=6q = 6.

16. Without switches, the 2222 lost units disappear, and round robin with q=1q = 1 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 q=2q = 2 or 33, where each takes longer turns.

17. No: with the same switch cost of 11, shortest job first gives 26.026.0 (24.024.0 if switches were free). A is alone at time 00 and, once started, runs to its end; the short processes all wait 2020 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. 4/4004≈0.1 %4 / 4004 \approx 0.1\,\% of the time. Here, with q=6q = 6 and a switch of 11, up to 1/71/7, about 14 %14\,\%: 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 2020 units and four of 22 to 66, with a switch costing one unit, round robin with a quantum of 66 gives the smallest mean turnaround, 20.220.2 units, against 27.427.4 for first come, first served and 32.832.8 for a quantum of 11.

本章定义的术语

在术语表中查看全部 1050 个术语