---
title: "Processes and Scheduling"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 31
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/31-processes-and-scheduling
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 31 — Processes 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](#def-g12-processes-and-scheduling-process), from the operating system’s side: how it is created, the [states](#def-g12-processes-and-scheduling-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](#def-g12-processes-and-scheduling-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](https://one-course.com/books/computer-science/2/en/chapter/14-operating-systems-and-the-command-line#def-g11-os-and-command-line-kernel) is the part of the operating system that manages the hardware and runs programs; programs ask it for services by [system calls](https://one-course.com/books/computer-science/2/en/chapter/14-operating-systems-and-the-command-line#def-g11-os-and-command-line-kernel), and the shell starts commands (chapter [14](https://one-course.com/books/computer-science/2/en/chapter/14-operating-systems-and-the-command-line#ch-g11-os-and-command-line)). A [state machine](https://one-course.com/books/computer-science/2/en/chapter/10-sensors-actuators-and-control-programs#def-g10-sensors-actuators-control-state-machine) moves between [states](#def-g12-processes-and-scheduling-states) on events (chapter [10](https://one-course.com/books/computer-science/2/en/chapter/10-sensors-actuators-and-control-programs#ch-g10-sensors-actuators-control)). A queue serves its elements first in, first out (chapter [24](https://one-course.com/books/computer-science/2/en/chapter/24-linked-lists-stacks-and-queues#ch-g12-lists-stacks-queues)). A cycle in a [directed graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-directed) is a path that comes back to its start (chapter [26](https://one-course.com/books/computer-science/2/en/chapter/26-graph-traversals-and-shortest-paths#ch-g12-graph-algorithms)).

## 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](#def-g12-processes-and-scheduling-process) creates another by a [system call](https://one-course.com/books/computer-science/2/en/chapter/14-operating-systems-and-the-command-line#def-g11-os-and-command-line-kernel); the new one is its *child*. In Python, the module `subprocess` starts a child and waits for it.

```python
"""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](#def-g12-processes-and-scheduling-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: $0$ 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](#def-g12-processes-and-scheduling-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](#def-g12-processes-and-scheduling-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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-processes-and-scheduling/fig-bc4deeadf48d.svg)

*The [states](#def-g12-processes-and-scheduling-states) of a [process](#def-g12-processes-and-scheduling-process) as a [state machine](https://one-course.com/books/computer-science/2/en/chapter/10-sensors-actuators-and-control-programs#def-g10-sensors-actuators-control-state-machine). Only the [scheduler](#def-g12-processes-and-scheduling-scheduler) moves a [process](#def-g12-processes-and-scheduling-process) into *running*; a blocked [process](#def-g12-processes-and-scheduling-process) always goes back through *ready*, even when its event is over.*

The output of `ps` above uses letters for these [states](#def-g12-processes-and-scheduling-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](https://one-course.com/books/computer-science/2/en/chapter/14-operating-systems-and-the-command-line#def-g11-os-and-command-line-kernel). A timer, the network card or the disk controller each sends interrupts; the [kernel](https://one-course.com/books/computer-science/2/en/chapter/14-operating-systems-and-the-command-line#def-g11-os-and-command-line-kernel)’s function decides what happens next.

A timer [interrupts](#def-g12-processes-and-scheduling-interrupt) the processor at a regular pace, many times a second. Each time, the [kernel](https://one-course.com/books/computer-science/2/en/chapter/14-operating-systems-and-the-command-line#def-g11-os-and-command-line-kernel) can take the processor away from the running [process](#def-g12-processes-and-scheduling-process) and give it to another.

**Definition 31.4 (Scheduler, quantum, round robin).**

The *scheduler* is the part of the [kernel](https://one-course.com/books/computer-science/2/en/chapter/14-operating-systems-and-the-command-line#def-g11-os-and-command-line-kernel) that chooses which ready [process](#def-g12-processes-and-scheduling-process) runs next. A *quantum* is the longest time a [process](#def-g12-processes-and-scheduling-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](#def-g12-processes-and-scheduling-process) to its end, in order of arrival.

**Definition 31.5 (Context switch).**

A *context switch* is the work of the [kernel](https://one-course.com/books/computer-science/2/en/chapter/14-operating-systems-and-the-command-line#def-g11-os-and-command-line-kernel) to stop one [process](#def-g12-processes-and-scheduling-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](#def-g12-processes-and-scheduling-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](#def-g12-processes-and-scheduling-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.

```python
"""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](#def-g12-processes-and-scheduling-scheduler), simulated. code/grade-12/10-processes-and-scheduling/listings/scheduler.py*

```python
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](#def-g12-processes-and-scheduling-process), and a Gantt line of text. code/grade-12/10-processes-and-scheduling/listings/scheduler.py*

```python
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](#def-g12-processes-and-scheduling-process). [Round robin](#def-g12-processes-and-scheduling-scheduler) starts every [process](#def-g12-processes-and-scheduling-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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-processes-and-scheduling/fig-a48355572a38.svg)

*[Round robin](#def-g12-processes-and-scheduling-scheduler) with a [quantum](#def-g12-processes-and-scheduling-scheduler) of $2$ on the workload of the listing. A, B, C and D arrive at times $0$ to $3$. Each [process](#def-g12-processes-and-scheduling-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$.*

The choice of the [quantum](#def-g12-processes-and-scheduling-scheduler) is a compromise. A short [quantum](#def-g12-processes-and-scheduling-scheduler) gives each [process](#def-g12-processes-and-scheduling-process) a turn soon, which is what a person at a keyboard notices; but each switch costs time. A long [quantum](#def-g12-processes-and-scheduling-scheduler) wastes little in switches, but [round robin](#def-g12-processes-and-scheduling-scheduler) 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* $1$ to the register, *store* the register back. The program below plays two such processes in every possible order.

```python
"""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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-processes-and-scheduling/fig-0471776f76fc.svg)

*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.*

**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](#def-g12-processes-and-scheduling-process) is in a critical section at any time. A *lock* provides it: a [process](#def-g12-processes-and-scheduling-process) *acquires* the lock before the critical section and *releases* it after; a [process](#def-g12-processes-and-scheduling-process) that tries to acquire a lock already held waits until it is released.

```python
"""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](#def-g12-processes-and-scheduling-race), 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](#def-g12-processes-and-scheduling-race) first does its three steps alone: the counter is always $2$.*

A real [lock](#def-g12-processes-and-scheduling-race) 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](#def-g12-processes-and-scheduling-race) on them.

## 31.5 Deadlock

**Definition 31.7 (Deadlock).**

A *deadlock* is a state in which each [process](#def-g12-processes-and-scheduling-process) of a group waits for a resource held by another [process](#def-g12-processes-and-scheduling-process) of the group, so that none of them can ever go on.

The simplest case needs two [locks](#def-g12-processes-and-scheduling-race). P takes A, then B; Q takes B, then A. If each takes its first [lock](#def-g12-processes-and-scheduling-race) before the other takes its second, both wait for ever.

```python
"""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](#def-g12-processes-and-scheduling-race). code/grade-12/10-processes-and-scheduling/listings/deadlock_sim.py*

```python
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](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph), and the two orders of taking the [locks](#def-g12-processes-and-scheduling-race). 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](#def-g12-processes-and-scheduling-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.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-processes-and-scheduling/fig-a9c1ef17de41.svg)

*The resource-allocation [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) of the [deadlock](#def-g12-processes-and-scheduling-deadlock). Processes are circles, [locks](#def-g12-processes-and-scheduling-race) squares; an arrow from a [lock](#def-g12-processes-and-scheduling-race) to a [process](#def-g12-processes-and-scheduling-process) means “held by”, from a [process](#def-g12-processes-and-scheduling-process) to a [lock](#def-g12-processes-and-scheduling-race) “waits for”. The four arrows form a cycle. Leaving out the [locks](#def-g12-processes-and-scheduling-race) gives the wait-for [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) of the output: P waits for Q, Q waits for P.*

A [deadlock](#def-g12-processes-and-scheduling-deadlock) needs four conditions together: *[mutual exclusion](#def-g12-processes-and-scheduling-race)* (a resource is held by one [process](#def-g12-processes-and-scheduling-process) at a time), *hold and wait* (a [process](#def-g12-processes-and-scheduling-process) keeps what it holds while it waits for more), *no preemption* (a resource cannot be taken away from the [process](#def-g12-processes-and-scheduling-process) holding it), and *circular wait* (a cycle of processes, each waiting for the next). Breaking any one prevents [deadlock](#def-g12-processes-and-scheduling-deadlock). The usual remedy breaks the fourth: number the resources, and have every [process](#def-g12-processes-and-scheduling-process) take them in increasing order. A cycle would then need a [process](#def-g12-processes-and-scheduling-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](#def-g12-processes-and-scheduling-deadlock)”, a survey published in 1971 in *ACM Computing Surveys*.

## 31.6 Exercises

**Exercise 31.1 ★.**

Three processes arrive at time $0$ in the order X (burst $4$), Y ($1$), Z ($3$). Give the order and the slices of first come, first served.

**Solution of Exercise 31.1.**

In order of arrival: X from $0$ to $4$, Y from $4$ to $5$, Z from $5$ to $8$. The Gantt line is `XXXXYZZZ`.

**Exercise 31.2 ★.**

Compute the waiting time of each [process](#def-g12-processes-and-scheduling-process) of exercise [31.1](#exo-g12-processes-and-scheduling-1), and the mean.

**Solution of Exercise 31.2.**

X waits $0$, Y waits $4$, Z waits $5$: a mean of $9/3 = 3$.

**Exercise 31.3 ★.**

Write the Gantt line of [round robin](#def-g12-processes-and-scheduling-scheduler) with a [quantum](#def-g12-processes-and-scheduling-scheduler) of $1$ on X, Y, Z of exercise [31.1](#exo-g12-processes-and-scheduling-1).

**Solution of Exercise 31.3.**

`XYZXZXZX`. Y is done after its first unit; Z after its third turn, at time $7$; X runs alone at the end.

**Exercise 31.4 ★.**

How many [context switches](#def-g12-processes-and-scheduling-context-switch) does [round robin](#def-g12-processes-and-scheduling-scheduler) with $q = 2$ make on the workload of the chapter? And with $q = 4$?

**Solution of Exercise 31.4.**

A switch happens each time the next slice belongs to another [process](#def-g12-processes-and-scheduling-process). With $q = 2$ the $10$ slices are A, B, C, A, D, B, C, A, C, C: $8$ switches, since C’s last two slices follow each other. With $q = 4$ the $6$ slices A, B, C, D, A, C make $5$.

**Exercise 31.5 ★.**

Write `turnaround(workload, slices)`, which returns the turnaround of each [process](#def-g12-processes-and-scheduling-process) as a dictionary.

**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](#def-g12-processes-and-scheduling-process) finishes.

**Exercise 31.6 ★★.**

A [round robin](#def-g12-processes-and-scheduling-scheduler) forgets to put an unfinished [process](#def-g12-processes-and-scheduling-process) back in the queue. What happens on the workload of the chapter with $q = 2$?

**Solution of Exercise 31.6.**

Each [process](#def-g12-processes-and-scheduling-process) runs once, for at most $2$ units: A from $0$ to $2$, B from $2$ to $4$, C from $4$ to $6$, D from $6$ to $8$. Then the queue is empty and the simulation stops. Only D, whose burst is $2$, has finished; A, B and C are left with $3$, $1$ and $6$ units, and will never run again. The tests check these remainders.

**Exercise 31.7 ★★.**

How many interleavings do two processes of $3$ steps each have? Of $a$ and $b$ steps? Explain the count.

**Solution of Exercise 31.7.**

$20$. An interleaving of $6$ steps is fixed by choosing which $3$ of the $6$ places hold P’s steps, in their own order; the other places hold Q’s. There are $\binom{6}{3} = 20$ such choices. For $a$ and $b$ steps: $\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](#def-g12-processes-and-scheduling-process) with the smallest burst. Apply it to the workload of the chapter.

**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 $0$ and runs to $5$; then D ($2$), B ($3$) and C ($8$): D from $5$ to $7$, B to $10$, C to $18$. Turnarounds $5$, $9$, $16$, $4$: a mean of $8.5$, against $10.25$ for first come, first served.

**Exercise 31.9 ★★.**

A function acquires a [lock](#def-g12-processes-and-scheduling-race), and returns early, without releasing it, when the value it reads is negative. What happens to the other processes that use the [lock](#def-g12-processes-and-scheduling-race)?

**Solution of Exercise 31.9.**

The [lock](#def-g12-processes-and-scheduling-race) stays held by a [process](#def-g12-processes-and-scheduling-process) that has left the [critical section](#def-g12-processes-and-scheduling-race). Every other [process](#def-g12-processes-and-scheduling-process) that tries to acquire it waits for ever, and so does the same [process](#def-g12-processes-and-scheduling-process) on its next call. The fix releases the [lock](#def-g12-processes-and-scheduling-race) on every path: in Python, `with lock:` around the [critical section](#def-g12-processes-and-scheduling-race), 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 of Exercise 31.10.**

P loads $0$; Q loads $0$, adds, stores $1$; P adds to its own copy, $1$, and stores $1$. The final counter is $1$: 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](#def-g12-processes-and-scheduling-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](#def-g12-processes-and-scheduling-deadlock) does each design rule out?

**Solution of Exercise 31.11.**

The first design rules out [mutual exclusion](#def-g12-processes-and-scheduling-race) as far as the processes are concerned: none of them ever holds the printer, only the server does, so no [process](#def-g12-processes-and-scheduling-process) can wait for another to give it back. The second rules out hold and wait: a [process](#def-g12-processes-and-scheduling-process) that waits holds nothing, and a [process](#def-g12-processes-and-scheduling-process) that holds its resources never waits for more.

**Exercise 31.12 ★★★.**

Prove that with the [lock](#def-g12-processes-and-scheduling-race), no run of `with_lock.py` loses an update, whatever the order of the steps.

**Solution of Exercise 31.12.**

Between its `acquire` and its `release`, a [process](#def-g12-processes-and-scheduling-process) holds the [lock](#def-g12-processes-and-scheduling-race), and the other cannot pass its own `acquire`. So the three steps of one [process](#def-g12-processes-and-scheduling-process) are never interleaved with those of the other: one [process](#def-g12-processes-and-scheduling-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](#def-g12-processes-and-scheduling-process) loads the value $1$ stored by the first and stores $2$. Steps outside the [lock](#def-g12-processes-and-scheduling-race) are only `acquire` and `release`, which do not touch the counter. The program finds the same: exactly $2$ runs, both ending at $2$.

**Exercise 31.13 ★★★.**

Write `has_cycle(waits_for)`, which detects a [deadlock](#def-g12-processes-and-scheduling-deadlock) in a wait-for [graph](https://one-course.com/books/computer-science/2/en/chapter/9-graphs-networks-of-roads-and-people#def-g10-graphs-first-look-graph) given as a dictionary from each [process](#def-g12-processes-and-scheduling-process) to the list of processes it waits for.

**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 $0$ with bursts $6$, $8$, $3$, $2$. 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 of Exercise 31.14.**

First come, first served: waits $0$, $6$, $14$, $17$, a mean of $37/4 = 9.25$. Shortest job first runs $2$, $3$, $6$, $8$: waits $0$, $2$, $5$, $11$, a mean of $18/4 = 4.5$.

When all arrive at $0$, the [process](#def-g12-processes-and-scheduling-process) in place $k$ (from $1$ to $n$) makes the $n - 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 $b$ comes just before a shorter one $c < b$. Swapping the two changes nothing for the others, and changes the total by $c - 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 $24$ 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](#def-g12-processes-and-scheduling-deadlock) can happen, and that taking the lower-numbered fork first prevents it.

**Solution of Exercise 31.15.**

Number the philosophers and forks $0$ to $4$; philosopher $k$ uses forks $k$ and $k + 1$ (fork $0$ 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](#def-g12-processes-and-scheduling-deadlock). With the rule “lower-numbered fork first”, philosophers $0$ to $3$ still start on the left, but philosopher $4$ starts with fork $0$. A cycle would need each philosopher to hold one fork and wait for a higher-numbered one; philosopher $4$ would hold fork $0$ and wait for fork $4$, but then philosopher $0$ holds nothing, and the cycle breaks. The function `philosophers` tries every reachable state and confirms: a [deadlock](#def-g12-processes-and-scheduling-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](#def-g12-processes-and-scheduling-context-switch) costs one unit of time. The program tries [round robin](#def-g12-processes-and-scheduling-scheduler) with every [quantum](#def-g12-processes-and-scheduling-scheduler) from $1$ to $12$.

```python
"""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](#def-g12-processes-and-scheduling-scheduler) on one workload, for every [quantum](#def-g12-processes-and-scheduling-scheduler). 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 $35$ ?
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](#def-g12-processes-and-scheduling-process) under first come, first served, and check the mean printed.

**Part II — Short and long quanta.**

5. Why is [round robin](#def-g12-processes-and-scheduling-scheduler) with $q = 1$ worse than first come, first served here?
6. Count the time lost in switches for $q = 1$ , and check it against the time when everything is done.
7. Why is the result the same for every $q \ge 20$ ? Which schedule is it?
8. Why do $q = 12$ and first come, first served differ, although A runs first in both?

**Part III — The best quantum.**

9. Which [quantum](#def-g12-processes-and-scheduling-scheduler) gives the smallest mean turnaround? By how much does it beat first come, first served?
10. With $q = 6$ , write the slices, and find when each [process](#def-g12-processes-and-scheduling-process) finishes.
11. Explain why $q = 6$ suits this workload: compare it with the bursts of the short processes.
12. Why does the mean grow again for $q$ from $7$ to $12$ ?
13. The mean does not change steadily with $q$ : $q = 5$ is worse than $q = 4$ . Compare the finishing time of each [process](#def-g12-processes-and-scheduling-process) for the two quanta, and explain.

**Part IV — Other measures.**

14. Compute the response time of B under first come, first served and under $q = 6$ .
15. A person typing in an editor cares about the response time; a person waiting for a report, about the turnaround. Which [quantum](#def-g12-processes-and-scheduling-scheduler) would each prefer here?
16. If a switch cost nothing, the program gives a mean turnaround of $17.4$ for $q = 1$ , and $17.0$ for $q = 2$ and $q = 3$ . Why does $q = 1$ improve so much, and why is it still not the best?
17. Shortest job first is not [round robin](#def-g12-processes-and-scheduling-scheduler) . Would it beat the best [quantum](#def-g12-processes-and-scheduling-scheduler) on this workload? Why can a real [scheduler](#def-g12-processes-and-scheduling-scheduler) not use it directly?
18. Suppose a [quantum](#def-g12-processes-and-scheduling-scheduler) of $4$ milliseconds and a switch costing $4$ microseconds. What fraction of the processor time goes to switches when every [quantum](#def-g12-processes-and-scheduling-scheduler) is used in full? Compare with $q = 6$ here.
19. Why do real systems also change the [quantum](#def-g12-processes-and-scheduling-scheduler) , or the order, for processes that often block?
20. State the result: the best [quantum](#def-g12-processes-and-scheduling-scheduler) for this workload and switch cost, its mean turnaround, and that of first come, first served.

**Solution of Problem 31.1.**

**1.** $20 + 3 + 6 + 2 + 4 = 35$ units.

**2.** The core does one unit of work per unit of time, and the work starts at $0$, so at least $35$; five processes also need at least four switches, so at least $39$.

**3.** By arrival, with a switch between each: A from $0$ to $20$, B $21$–$24$, C $25$–$31$, D $32$–$34$, E $35$–$39$.

**4.** $20$, $23$, $29$, $31$, $34$: $137 / 5 = 27.4$, the value printed.

**5.** Each unit of work is followed by a switch, so $22$ units are lost. B, D and E finish sooner than under first come, first served (turnarounds $20$, $16$, $30$ against $23$, $31$, $34$), but C, sharing the core one unit at a time, takes $41$ instead of $29$, and A $57$ instead of $20$. The total grows by $27$ units, the mean by $5.4$.

**6.** $22$ switches of $1$ unit, and $35 + 22 = 57$, the time printed: the core is never idle.

**7.** With $q \ge 20$, every [process](#def-g12-processes-and-scheduling-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 = 20$ to $29$.

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

**9.** $q = 6$, with $20.2$: $7.2$ less than first come, first served.

**10.** A $0$–$6$, B $7$–$10$, C $11$–$17$, D $18$–$20$, E $21$–$25$, then A alone from $26$ to $40$. B, C, D and E finish at $10$, $17$, $20$, $25$; A at $40$.

**11.** $6$ is the longest burst of the short processes ($3$, $6$, $2$, $4$): each of them finishes in one turn, while A, the long one, is interrupted once and goes to the back.

**12.** Every short [process](#def-g12-processes-and-scheduling-process) already finishes in one turn, so a longer [quantum](#def-g12-processes-and-scheduling-scheduler) only lengthens A’s first slice: B, C, D and E each finish one unit later per unit of [quantum](#def-g12-processes-and-scheduling-scheduler). The total grows by $4$, the mean by $0.8$, as printed.

**13.** Finishing times for $q = 4$: A $42$, B $8$, C $29$, D $16$, E $26$; for $q = 5$: A $42$, B $9$, C $31$, D $18$, E $23$. A’s first slice is one unit longer, which delays B by $1$; C needs a second turn in both cases, and everything before it is longer, so C and D lose $2$. E gains $3$: it arrives at $5$, which with $q = 5$ is exactly when A’s slice ends, so E joins the queue before A; with $q = 4$, A is back in the queue at $4$, ahead of E. In all $+1 + 2 + 2 - 3 = +2$ units, so the mean grows by $0.4$.

**14.** First come, first served: B arrives at $1$ and starts at $21$, a response time of $20$. With $q = 6$: it starts at $7$, a response of $6$.

**15.** The typist wants short response times, so a short [quantum](#def-g12-processes-and-scheduling-scheduler): with $q = 1$ every [process](#def-g12-processes-and-scheduling-process) starts within a few units. The person waiting for a report wants the short turnarounds of $q = 6$.

**16.** Without switches, the $22$ lost units disappear, and [round robin](#def-g12-processes-and-scheduling-scheduler) with $q = 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 = 2$ or $3$, where each takes longer turns.

**17.** No: with the same switch cost of $1$, shortest job first gives $26.0$ ($24.0$ if switches were free). A is alone at time $0$ and, once started, runs to its end; the short processes all wait $20$ units. [Round robin](#def-g12-processes-and-scheduling-scheduler) [interrupts](#def-g12-processes-and-scheduling-interrupt) A, which shortest job first never does. A real [scheduler](#def-g12-processes-and-scheduling-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 \approx 0.1\,\%$ of the time. Here, with $q = 6$ and a switch of $1$, up to $1/7$, about $14\,\%$: the toy cost is more than a hundred times heavier.

**19.** A [process](#def-g12-processes-and-scheduling-process) that blocks often, waiting for a key or the network, uses little of its [quantum](#def-g12-processes-and-scheduling-scheduler), 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 $20$ units and four of $2$ to $6$, with a switch costing one unit, [round robin](#def-g12-processes-and-scheduling-scheduler) with a [quantum](#def-g12-processes-and-scheduling-scheduler) of $6$ gives the smallest mean turnaround, $20.2$ units, against $27.4$ for first come, first served and $32.8$ for a [quantum](#def-g12-processes-and-scheduling-scheduler) of $1$.**
