Skip to contents
OpenLearningTHE STUDY LIBRARY

In depth study guide · Edition 2026.12

Operating systems, from processes to persistence

An illustrated, practical foundation with safe local experiments and complete answers

A substantial original guide to processes, scheduling, virtual memory, concurrency, files, crash behavior, I/O, isolation, and resource-aware programs.

14 chapters14 diagrams28 practice tasks

Before you begin

How to use this guide

Developers and students who can read small programs and want to reason clearly about the machine beneath them.

Helpful background

What you will be able to do

A useful study rhythm

Read the explanation, close the book, and draw or explain the idea from memory. Predict each example before running or tracing it. Attempt the chapter exercises, compare your reasoning with the solution manual, and return to the source when an assumption changes.

For a first pass, follow the chapter order. For revision, use the contents and glossary. Assessment answers and exercise solutions are separated from the questions so you can retrieve an answer before seeing it. Internal links and bookmarks work in most PDF readers; the printed page number helps when reading on paper.

Scope and assumptions

Core explanations and original diagrams are available offline. External books, videos, and documentation remain at their publishers’ sites and may require an internet connection or a separate account.

Chapter 01

Meet the operating system without memorizing a list

Explain why applications need protected access to shared hardware.

By the end of this chapter
  • Separate a program, process, kernel, and system call
  • Recognize abstraction, isolation, and resource-sharing tradeoffs

The problem an operating system solves

Several applications want the same finite machine at once. A music player needs timely audio, a browser needs memory and network access, and a file copy needs storage bandwidth. Letting each application control every device and every memory location directly would make accidental interference routine. An operating system coordinates access, supplies useful abstractions, and enforces boundaries. Its decisions affect correctness as well as performance: a fast program is not useful if it can silently overwrite another program’s memory.

The kernel is the privileged core responsible for mechanisms such as managing address spaces, scheduling execution, and handling device interactions. User-space programs run with more restricted access and ask for protected operations through system calls. A library function is not necessarily a system call: it may calculate entirely in user space, buffer several operations, or invoke multiple kernel services. When a program writes text, layers of language runtime, library buffering, kernel interfaces, and device handling can be involved.

A protected request for a resourceAn application calls a library, the library may invoke a system call, and the kernel checks and performs privileged resource work before returning a result.ApplicationRequests a useful operationRuntime or libraryEncodes arguments and may buffer workSystem-call boundaryEnter the kernel through a controlled interfaceKernel and deviceValidate, schedule, perform, and report the result
A protected request for a resource. An application calls a library, the library may invoke a system call, and the kernel checks and performs privileged resource work before returning a result.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [2] MIT xv6 RISC-V teaching operating system, 2024 course page · [3] MIT 6.S081 Operating System Engineering, Fall 2020 video schedule

Observe an abstraction before assuming its implementation

Ask about this process python
import os
import platform
print("positive pid:", os.getpid() > 0)
print("platform:", platform.system())
Expected result
positive pid: True
platform: Darwin, Linux, or Windows, depending on the host

A process identifier is a handle used to refer to a process in a particular context, not a permanent identity for the application’s whole lifetime across restarts. A filename similarly names an object through a namespace; it is not the physical storage location. Abstractions simplify work by hiding details, but troubleshooting sometimes requires you to look beneath them. Ask which layer owns the observed state, which guarantees are documented, and which details vary across systems.

This guide uses Unix-like terminology and portable Python for most experiments. Linux-specific tools and kernel mechanisms are labeled. macOS has many related interfaces but is not Linux, while Windows has different native process and I/O models. The small scheduling and memory simulators are teaching models; they do not claim to reproduce every policy of a current production kernel. That separation lets you learn durable ideas without mistaking one diagram for every real machine.

Go deeper: [19] Python 3.11 operating-system interfaces · [1] Operating Systems: Three Easy Pieces, version 1.10

Keep these ideas

  • Useful abstractions come with boundaries and costs.
  • A library call, system call, and device operation are different events.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

1.1 · Practice task

Why might print("hello") involve no immediate device write at that exact statement?

Hint: Consider buffering between the language and the device.

Read the worked solution

1.2 · Practice task

A process reports a very large virtual address space. Does it necessarily own that much physical RAM?

Hint: An address space is an abstraction with mappings and permissions.

Read the worked solution

Chapter 02

Create, run, wait for, and clean up processes

Treat process lifecycle as a resource protocol rather than just starting a command.

By the end of this chapter
  • Distinguish fork, exec, exit, and wait
  • Launch a child safely and inspect its outcome

A program becomes a running process

A program is stored instructions and data in a form that can be loaded. A process is an executing instance with state: an address space, execution context, open resources, and identity information. Two processes can run the same program while keeping distinct private state. Conversely, a process can replace the program it runs. On Unix-like systems, fork and exec illustrate that separation: fork creates a child process, while an exec-family operation replaces the calling process’s program image.

After fork, parent and child continue from the fork result but receive different return values. Their private address spaces are logically separate, often implemented efficiently with copy-on-write until a write requires distinct pages. Some resources, such as references to open file descriptions, have sharing relationships that matter. Forking a multithreaded program has extra hazards because only the calling thread continues in the child while inherited lock state may reflect vanished threads. Prefer a documented high-level process API for ordinary tasks.

The Unix-like process lifecycleA parent starts a child, the child can replace its program, execution ends with an exit status, and the parent collects the result.ParentCreate a child using an appropriate APIChild setupPrepare arguments and allowed resourcesNew programExecute its instructionsExit and waitRelease resources and collect termination status
The Unix-like process lifecycle. A parent starts a child, the child can replace its program, execution ends with an exit status, and the parent collects the result.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [4] Linux fork manual · [5] Linux execve manual · [6] Linux wait manual

Own the child until its result is collected

Run a child without an intervening shell python
import subprocess
import sys
result = subprocess.run(
    [sys.executable, "-c", "print(6 * 7)"],
    capture_output=True, text=True, timeout=2, check=True)
print(result.stdout.strip())
print(result.returncode)
Expected result
42
0

Passing an argument list with shell=False avoids interpreting ordinary data as shell syntax. It does not make an unsafe invoked program safe; you must still choose the executable and arguments appropriately. Capture only bounded output in real services, because a child can produce more output than memory can hold. Use a timeout when the caller cannot wait indefinitely, and understand the API’s process-tree and platform-specific cancellation behavior.

When a child terminates, the parent should collect its status through wait or a higher-level equivalent. A Unix zombie retains a small termination record until it is reaped; it is not a running worker consuming CPU. An orphan is a different relationship involving the loss of the original parent. Do not treat every process-state label as a reason to send an uncatchable signal. First establish who owns the process and what cleanup contract should apply.

Go deeper: [20] Python 3.11 subprocess reference · [6] Linux wait manual

Keep these ideas

  • Starting a child also creates a cleanup responsibility.
  • Arguments are data only when they are kept out of shell syntax.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

2.1 · Practice task

Does a successful exec-family call normally return to execute the next line of the old program?

Hint: What does replacing the program image imply?

Read the worked solution

2.2 · Practice task

Why should a service avoid starting unlimited subprocesses for incoming requests?

Hint: Each child needs finite kernel and user-space resources.

Read the worked solution

Chapter 03

Understand threads, states, and context switching

Explain concurrency without assuming simultaneous execution.

By the end of this chapter
  • Compare process isolation with thread sharing
  • Trace ready, running, and blocked states

One process can contain several execution paths

A thread is an execution context within a process. Threads commonly share the process’s address space and many resources while keeping their own stacks and register state. Sharing makes communication convenient but also creates opportunities for one thread to observe another’s unfinished update. Separate processes usually begin with stronger private-memory boundaries, although explicit shared memory and communication channels can cross them. The correct choice depends on failure containment, communication cost, and the work being performed.

Concurrency means multiple activities can make progress over overlapping periods. Parallelism means work actually executes at the same time on distinct execution resources. A single CPU core can interleave several runnable threads without executing all of them simultaneously. A thread can also block while waiting for I/O or synchronization. At that point another runnable thread can use CPU time. The distinction explains why concurrency can help an I/O-heavy application even when CPU parallel speedup is limited.

StateMeaning in a simplified modelTypical next event
ReadyAble to run but waiting for CPU timeScheduler dispatches it
RunningCurrently executingPreemption, block, or completion
BlockedWaiting for an event or conditionI/O or synchronization makes it ready
The state transitions matter more than a sloganA runnable thread can be dispatched, block on an event, become ready again, and later finish; blocked time is different from CPU execution.ReadyWaiting for a turn on a CPURunningExecuting instructionsBlockedWaiting for I/O or a conditionReady againThe event occurred; execution still needs scheduling
The state transitions matter more than a slogan. A runnable thread can be dispatched, block on an event, become ready again, and later finish; blocked time is different from CPU execution.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [2] MIT xv6 RISC-V teaching operating system, 2024 course page · [21] Python 3.11 threading reference

A context switch is useful work with a cost

A context switch saves enough execution state to resume one activity later and restores another’s state. The cost includes direct bookkeeping and possible indirect effects on caches and translation information. A switch is not inherently a mistake: without switching, one waiting or long-running activity could make the machine unresponsive. The engineering question is whether the amount of concurrency helps the workload enough to justify coordination and scheduling costs.

Join a bounded pair of threads python
from threading import Thread
from queue import Queue
results = Queue()
def work(value):
    results.put(value * value)
threads = [Thread(target=work, args=(x,)) for x in (2, 3)]
for thread in threads: thread.start()
for thread in threads: thread.join(timeout=2)
assert all(not thread.is_alive() for thread in threads)
print(sorted(results.get() for _ in threads))
Expected result
[4, 9]

The sorted result avoids claiming a fixed completion order. The queue supplies a documented coordination mechanism rather than relying on incidental timing. For standard CPython 3.11 builds, the interpreter lock limits simultaneous execution of Python bytecode by threads; I/O can still overlap. This is a runtime-specific property, not the definition of an operating-system thread, and newer interpreter configurations can differ. Measure the actual runtime and workload before promising a speedup.

Go deeper: [21] Python 3.11 threading reference · [22] Python 3.11 queue reference

Keep these ideas

  • Shared memory makes coordination a correctness requirement.
  • Join workers and avoid assumptions about incidental scheduling order.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

3.1 · Practice task

Can two concurrent tasks on one CPU core be making useful progress without running at the exact same instant?

Hint: Progress across an interval is different from simultaneous execution.

Read the worked solution

3.2 · Practice task

Why is completion order unspecified in the queue example, and why is sorting acceptable here?

Hint: The example’s contract is a set of square results, not a race winner.

Read the worked solution

Chapter 04

Calculate scheduling tradeoffs with small timelines

Use response time, turnaround, and waiting time to compare policies.

By the end of this chapter
  • Calculate basic scheduling metrics
  • Explain why teaching policies are not current-kernel specifications

Choose a metric before choosing a policy

A scheduler chooses which runnable work receives CPU time. Different goals compete: interactive response, throughput, fairness, predictable latency, and efficient use of hardware. Response time measures delay until a task first gets service. Turnaround measures completion time minus arrival time. Waiting time counts time ready but not running in a simplified CPU-only model. These are different metrics, so one policy can improve one while harming another.

For a first experiment, assume one CPU, all tasks arrive at time zero, no I/O, and negligible switching overhead. First-come-first-served runs tasks in arrival order to completion. If A needs 8 units, B needs 2, and C needs 1, completion times are 8, 10, and 11. Mean turnaround is 29/3, about 9.67. The assumptions are deliberately simple so every number can be checked. They do not describe a complete desktop workload.

Compute a first-come-first-served timeline python
tasks = [("A", 8), ("B", 2), ("C", 1)]
time = 0
turnaround = []
for name, burst in tasks:
    start = time
    time += burst
    turnaround.append(time)
    print(name, start, time)
print(round(sum(turnaround) / len(turnaround), 2))
Expected result
A 0 8
B 8 10
C 10 11
9.67

Go deeper: [3] MIT 6.S081 Operating System Engineering, Fall 2020 video schedule · [7] Linux scheduling overview

Preemption changes who waits

Shortest-job-first would run C, then B, then A in that simplified example, lowering mean turnaround to (1+3+11)/3 = 5. It assumes useful knowledge about future service time, and a stream of short work can harm long work under naive policies. Round-robin gives each ready task a bounded time slice before rotating it to the queue’s end. A short slice can improve initial response, but very frequent switches add overhead. A large slice begins to resemble running each task for a long uninterrupted period.

A round-robin teaching modelRunnable jobs wait in a queue. The scheduler selects the front job, runs up to one quantum, and requeues unfinished work. Real schedulers consider more state.Ready queueA, B, C are runnableDispatchChoose the next eligible taskTime sliceRun until quantum, block, or finishRequeue or completeUnfinished runnable work returns to consideration
A round-robin teaching model. Runnable jobs wait in a queue. The scheduler selects the front job, runs up to one quantum, and requeues unfinished work. Real schedulers consider more state.Scroll horizontally to read the full diagram on a small screen.

Real operating systems account for priority, multiple cores, affinity, blocking, wakeups, and policy-specific behavior. Linux scheduling implementation has evolved, so do not learn an unqualified claim that one named algorithm describes all current Linux tasks. The Linux scheduling API reference is useful for policies and interfaces, while kernel documentation explains a particular implementation. Use simulation to understand tradeoffs, then use the host’s tools to observe its actual behavior.

Go deeper: [8] Linux scheduler documentation · [7] Linux scheduling overview

Keep these ideas

  • State arrivals, I/O assumptions, and switch costs before calculating.
  • A teaching schedule explains a tradeoff, not an entire modern kernel.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

4.1 · Practice task

All tasks arrive at zero with CPU bursts A=6 and B=2. Compare mean turnaround for A-then-B and B-then-A.

Hint: Compute completion times, then average them.

Read the worked solution

4.2 · Practice task

Why can making a round-robin quantum extremely small harm throughput?

Hint: Switching has a cost and can disturb useful locality.

Read the worked solution

Chapter 05

Build a useful model of virtual memory

Separate the addresses a program uses from the physical memory backing them.

By the end of this chapter
  • Explain mappings, permissions, stack, heap, and shared regions
  • Distinguish virtual size, residency, and allocation

Each process sees its own address space

An address space is the set of addresses and mappings a process can use under its protection rules. A virtual address is translated through hardware-supported mechanisms and operating-system-maintained information to a physical location or another result such as a fault. Two processes can use the same numeric virtual address and reach different physical memory. The abstraction helps isolation, relocation, and controlled sharing; it is not merely a trick for pretending that a disk is RAM.

A process typically has code mappings, global data, dynamically allocated regions often called the heap, thread stacks, shared libraries, and mapped files. The exact arrangement depends on the system, executable format, runtime, and security features. A diagram with one growing heap and one descending stack is a useful simplified model but not a universal layout contract. Address randomization and multiple mapped regions make real maps more complex.

A simplified process address spaceCode, data, dynamic allocations, mappings, and stacks are distinct regions with permissions. Their order and size are illustrative, not fixed across operating systems.Code mappingInstructions, often readable and executableData and heap regionsGlobals and dynamic allocationsShared or mapped regionsLibraries, files, or explicit shared memoryThread stacksCall frames and local execution state
A simplified process address space. Code, data, dynamic allocations, mappings, and stacks are distinct regions with permissions. Their order and size are illustrative, not fixed across operating systems.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [9] Linux virtual-memory concepts · [10] Linux mmap manual

Allocation is a conversation between layers

Observe a small allocation without guessing physical addresses python
data = bytearray(4096)
data[0] = 7
view = memoryview(data)
view[1] = 9
print(data[:2].hex())
print(len(data))
Expected result
0709
4096

The example shows two Python-level views of the same mutable buffer, not raw physical memory. The runtime’s object allocator, virtual-memory mappings, and physical-page residency are different layers. A request to reserve address space need not mean every page immediately has physical backing. Touching a page can trigger additional work. Conversely, freeing a language object does not require the runtime to return every byte to the operating system at once.

When investigating memory, ask what is measured. Virtual size includes address-space reservations and mappings. Resident set measurements concern pages currently in physical memory under the tool’s accounting rules. Shared pages and caches complicate sums across processes. A high number is not automatically a leak; a leak means resources remain unintentionally retained or unusable as the program continues. Compare trends under a repeatable workload and inspect references or allocations before making a diagnosis.

Go deeper: [26] Python 3.11 memoryview documentation · [9] Linux virtual-memory concepts

Keep these ideas

  • Virtual addresses are interpreted through a process’s mappings.
  • Use the metric that matches the memory question.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

5.1 · Practice task

Two processes print the same numeric virtual pointer. Must they be sharing the same data?

Hint: Translation depends on address-space context.

Read the worked solution

5.2 · Practice task

Why can deleting a large Python object fail to reduce the process’s resident-memory measurement immediately?

Hint: The runtime and OS can retain memory for reuse.

Read the worked solution

Chapter 06

Translate addresses and explain page faults

Do a complete translation calculation before learning implementation variants.

By the end of this chapter
  • Split a virtual address into page number and offset
  • Distinguish a TLB miss from a page fault

Fixed-size pages simplify placement

Paging divides virtual memory into pages and physical memory into page frames. A page table records mappings and relevant state such as permissions or presence. With a 4,096-byte page in a teaching example, the low 12 address bits represent the offset within a page. The remaining bits identify the virtual page. Page size varies by architecture and mapping; 4 KiB is an example, not a promise about every machine or every page in one process.

To translate virtual address 0x2345 with 4-KiB pages, split it into virtual page 0x2 and offset 0x345. If the table maps virtual page 2 to physical frame 9, the physical address is frame base 0x9000 plus 0x345, giving 0x9345. The offset is preserved because translation chooses the frame containing the page’s corresponding bytes. Permissions are checked as part of the access rules, not ignored after finding a frame number.

A small page-translation model python
page_size = 4096
virtual_address = 0x2345
page, offset = divmod(virtual_address, page_size)
page_table = {2: 9}
physical = page_table[page] * page_size + offset
print(page, hex(offset), hex(physical))
Expected result
2 0x345 0x9345
Translate, then accessSplit the address, look up the mapping and permissions, combine a physical frame with the unchanged offset, then access memory if allowed.Virtual addressPage number plus offsetTranslation informationFind mapping and check access rightsPhysical addressFrame base plus the same offsetMemory accessRead or write permitted bytes
Translate, then access. Split the address, look up the mapping and permissions, combine a physical frame with the unchanged offset, then access memory if allowed.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [9] Linux virtual-memory concepts · [3] MIT 6.S081 Operating System Engineering, Fall 2020 video schedule

Cache translation and handle exceptional work

A translation lookaside buffer, TLB, caches address-translation information so ordinary accesses do not require a full page-table walk every time. A TLB miss means the cached translation was not found. The processor can often walk the tables and fill the TLB without an operating-system page-fault handler. A page fault is a different event requiring the system to handle a missing or disallowed access condition. Conflating the two makes both performance analysis and debugging confusing.

Not every page fault means data is read from a swap device. Demand-zero allocation, copy-on-write, and already-cached file pages can produce faults with different work involved. A protection violation may be invalid rather than recoverable. The kernel can create a mapping, wait for I/O, or report a fault to the process depending on the access and policy. Observe minor versus major fault terminology using the specific operating system’s definitions.

Worked example · Estimate translation overhead under explicit assumptions

  1. Assume a hypothetical 100-ns memory access, a 1-ns TLB check, and a single-level page table whose miss adds one 100-ns memory access.
  2. At a 99% TLB hit rate, the model gives 1 + 100 + 0.01×100 = 102 ns average.
  3. Real processors can overlap work and have multilevel caches/tables. The calculation teaches weighted costs; it is not a hardware benchmark.

Result: A rare expensive path can matter, and a simple model must state what it omits.

Go deeper: [9] Linux virtual-memory concepts · [2] MIT xv6 RISC-V teaching operating system, 2024 course page

Keep these ideas

  • Preserve the offset during page translation.
  • A translation-cache miss and a missing page are distinct events.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

6.1 · Practice task

With 1,024-byte pages, virtual address 2,500 maps through virtual page 2 to physical frame 7. Find offset and physical address.

Hint: Use quotient and remainder by the page size.

Read the worked solution

6.2 · Practice task

A TLB lookup misses but the page table contains a valid resident mapping. Must storage I/O happen?

Hint: A missing cached translation is not a missing physical page.

Read the worked solution

Chapter 07

Use locality to reason about caches and memory pressure

Learn replacement policies with a trace you can inspect.

By the end of this chapter
  • Explain temporal and spatial locality
  • Simulate LRU and reason about working sets

Programs revisit nearby and recent data

Temporal locality means recently used data is likely to be used again. Spatial locality means nearby data is likely to be accessed soon. These patterns make caches useful at several levels, from CPU caches to file caches. A sequential scan, a repeated small lookup table, and random access across a huge dataset have different locality. An optimization that helps one pattern can hurt another. Describe the access trace before claiming that a bigger cache or a different container is automatically faster.

The working set is the data actively needed over a meaningful interval. When active demand fits the available fast storage, reuse can be effective. When it greatly exceeds available physical memory, the system may spend substantial effort reclaiming and faulting pages instead of doing useful work. This can produce thrashing-like behavior. A single page-fault count is not enough to diagnose it; look at fault rates, I/O, memory pressure, and useful throughput together.

A locality feedback loopThe workload touches a set of pages, resident capacity determines reuse, misses trigger work, and the resulting stalls affect useful progress.Access patternWhich pages are touched, and how often?Resident working setHow much useful data stays available?Miss and reclaim workFetch, map, or evict when neededObserved progressMeasure throughput and waiting together
A locality feedback loop. The workload touches a set of pages, resident capacity determines reuse, misses trigger work, and the resulting stalls affect useful progress.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [9] Linux virtual-memory concepts · [1] Operating Systems: Three Easy Pieces, version 1.10

A replacement simulator makes tradeoffs concrete

Least-recently-used teaching simulation python
from collections import OrderedDict
frames = OrderedDict()
faults = 0
for page in [1, 2, 1, 3, 1, 2]:
    if page not in frames:
        faults += 1
        if len(frames) == 2:
            frames.popitem(last=False)
    else:
        del frames[page]
    frames[page] = None
print(faults)
print(list(frames))
Expected result
4
[1, 2]

The oldest dictionary entry represents the least recently used page. Reusing a page moves it to the recent end. On the trace, pages 1 and 2 first fault, the second access to 1 hits, page 3 evicts 2, the next 1 hits, and the final 2 faults. The four faults are a result of this exact capacity and trace. A real operating system cannot usually maintain perfect per-access LRU bookkeeping for all memory cheaply, so it uses implementation-specific approximations and other information.

Separate policy from mechanism. A mechanism can track access indicators, maintain lists, or move pages; a policy decides what to prefer under pressure. Replacement interacts with dirty pages, file-backed data, sharing, priorities, and reclaim costs. A clean page that can be reread may have a different eviction cost from a modified page requiring writeback. A good explanation says which resources and costs its simple model ignores.

Go deeper: [9] Linux virtual-memory concepts · [27] Python 3.11 collections reference

Keep these ideas

  • A cache policy can only exploit the workload’s available locality.
  • Use simulations for understanding and measurements for the actual host.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

7.1 · Practice task

Simulate LRU with two frames for accesses A, B, A, C, B. How many misses occur?

Hint: Move a hit to the most-recent position.

Read the worked solution

7.2 · Practice task

Why might adding workers reduce throughput on a memory-constrained machine?

Hint: Workers can compete for an active working set larger than available memory.

Read the worked solution

Chapter 08

Protect shared state with an explicit invariant

Find the operation that must remain indivisible from another thread’s point of view.

By the end of this chapter
  • Trace a lost update
  • Use locks for compound state changes and keep critical sections purposeful

A race is about allowed interleavings

Suppose two workers each add one to a shared counter. At a conceptual machine level, "add one" may involve reading the current value, calculating a new value, and writing it back. Both workers can read zero before either writes, then both write one. The intended result is two, but one update disappears. A race condition means the result depends incorrectly on timing or ordering. In languages with a formal memory model, unsynchronized conflicting memory accesses can have even stronger consequences than this simple lost-update story.

An invariant is a condition that should remain true at the boundaries visible to the rest of the program. For an account transfer, the sum of two balances may need to stay constant while neither balance becomes invalid. Protecting only one assignment can leave other threads observing half a transfer. Identify the whole state transition and its readers before choosing where to lock. A lock is a mechanism for coordination; it does not automatically identify the correct invariant for you.

How a lost update happensBoth workers read the same old value, calculate independently, and overwrite the shared counter with the same new value.Worker AShared counterWorker B1. Read 02. Read 0 before A writes3. Write 14. Write 1: A’s contribution is lost
How a lost update happens. Both workers read the same old value, calculate independently, and overwrite the shared counter with the same new value.Scroll horizontally to read the full diagram on a small screen.
Force the conceptual lost-update trace python
counter = 0
a_read = counter
b_read = counter
counter = a_read + 1
counter = b_read + 1
print(counter)
Expected result
1

Go deeper: [21] Python 3.11 threading reference · [2] MIT xv6 RISC-V teaching operating system, 2024 course page

Lock the state transition, then simplify sharing

A lock protects each increment python
from threading import Lock, Thread
lock = Lock()
counter = 0
def add_many():
    global counter
    for _ in range(1000):
        with lock:
            counter += 1
threads = [Thread(target=add_many) for _ in range(2)]
for thread in threads: thread.start()
for thread in threads: thread.join()
print(counter)
Expected result
2000

Every participant that accesses the protected state must follow the same synchronization discipline. One carefully locked writer cannot make an unsynchronized reader correct by magic. Keep critical sections small enough to avoid unnecessary blocking but large enough to preserve the invariant. Avoid performing slow network requests while holding a shared-state lock unless the design explicitly requires that coupling. A lock held across unpredictable I/O can turn one slow dependency into a queue for unrelated work.

Often the clearest fix is to reduce sharing: give each worker private results, then combine them in one place; pass messages through a queue; or use an immutable representation. These choices can make ownership easier to reason about. They still have costs and ordering questions, but the protected state becomes smaller. Do not rely on a particular CPython version’s convenient behavior as a universal proof that a compound algorithm is thread-safe.

Go deeper: [21] Python 3.11 threading reference · [22] Python 3.11 queue reference

Keep these ideas

  • Write the invariant before selecting the lock.
  • Less shared mutable state often means a simpler correctness argument.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

8.1 · Practice task

A transfer subtracts from account A and adds to account B. Why might locking only the addition fail?

Hint: Another reader can see the state between the two operations.

Read the worked solution

8.2 · Practice task

Why does an increment example printing the correct result once fail to prove it is race-free?

Hint: Correctness must cover all allowed interleavings, not one observed run.

Read the worked solution

Chapter 09

Wait for a condition without wasting a CPU

Use condition variables and bounded queues to coordinate useful work.

By the end of this chapter
  • Explain predicate-based waiting
  • Build a producer-consumer workflow with explicit termination

Sleeping and polling solve different problems

A worker may need to wait until data exists, space is available, or another task has finished. Repeatedly checking a flag in a tight loop can waste CPU time and create contention. Adding arbitrary sleeps can reduce CPU use but introduces delays and still fails to establish a correctness relationship. Proper waiting coordinates the state predicate and the wakeup mechanism so a worker does not miss the transition it needed to observe.

A condition variable is used with a lock protecting shared state. The worker checks a predicate while holding that lock, waits in a loop when the predicate is false, and rechecks after waking. Waiting releases the associated lock while the thread sleeps and reacquires it before returning. The loop matters because waking is a reason to recheck, not a promise that the desired state is still true. Another worker may have consumed the item first, and some APIs permit spurious wakeups.

Wait on a predicate, not on hopeAcquire the lock, inspect shared state, wait while the predicate is false, then perform the state transition while still following the lock discipline.Lock and inspectIs there an item or has shutdown been requested?Wait if falseRelease the lock atomically with entering the waitWake and recheckReacquire and evaluate the predicate againAct on valid stateConsume work or terminate deliberately
Wait on a predicate, not on hope. Acquire the lock, inspect shared state, wait while the predicate is false, then perform the state transition while still following the lock discipline.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [21] Python 3.11 threading reference · [22] Python 3.11 queue reference

A bounded queue supplies a useful ownership boundary

A producer and a worker with explicit completion python
from queue import Queue
from threading import Thread
work = Queue(maxsize=2)
results = []

def consume():
    while True:
        item = work.get()
        try:
            if item is None:
                return
            results.append(item * 2)
        finally:
            work.task_done()

worker = Thread(target=consume)
worker.start()
for item in (1, 2, 3):
    work.put(item)
work.put(None)
work.join()
worker.join()
print(results)
Expected result
[2, 4, 6]

The queue’s capacity applies backpressure: the producer waits when it has filled the allowed pending slots. That bounds one part of the system’s memory demand. The sentinel value None is a protocol choice meaning shutdown, so None cannot also be an ordinary item in this example. With several consumers, send an appropriate termination signal to each or use another documented shutdown design. Every successful get must be paired with task_done, including the sentinel, or join can wait forever.

The example uses one consumer, so result order follows the queued order. With multiple workers, completion order can differ even when dequeue order is FIFO. If results must be returned in input order, attach sequence numbers and reorder deliberately or use a suitable abstraction. Failure handling also needs design: an exception should not leave the queue’s bookkeeping inconsistent or silently lose a task that the application promises to process.

Go deeper: [22] Python 3.11 queue reference

Keep these ideas

  • A wakeup means recheck the predicate.
  • Bound queues and define shutdown and failure behavior.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

9.1 · Practice task

Why should a condition wait normally appear in a while loop rather than a single if?

Hint: A wakeup does not reserve the resource for one waiter.

Read the worked solution

9.2 · Practice task

What happens if a consumer calls get but forgets task_done for one item?

Hint: Queue join tracks unfinished-task bookkeeping, not just empty storage.

Read the worked solution

Chapter 10

Recognize deadlock, starvation, and unsafe lock ordering

Understand liveness failures separately from wrong numeric answers.

By the end of this chapter
  • Trace a circular wait
  • Choose an ordering or ownership design that breaks the cycle

A program can be wrong by never finishing

Deadlock occurs when activities wait for one another in a way that prevents the required progress. The classic two-lock example is small: worker A holds lock X and waits for Y, while worker B holds Y and waits for X. Each worker follows a locally understandable instruction, yet the combined state cannot advance. Correctness therefore includes liveness questions as well as the safety question of whether a completed result has the right value.

Four conditions are often used to analyze resource deadlock: mutual exclusion, holding resources while waiting for others, no forced preemption of those resources, and circular wait. They are a reasoning framework for the specified resource model, not a magical diagnostic command. Breaking a suitable condition can prevent the modeled deadlock, but the remedy has costs. For example, taking every lock at once can serialize too much work, and forcibly interrupting an operation can leave application state inconsistent.

The circular-wait trapA owns X and requests Y while B owns Y and requests X; neither releases what the other needs.Worker ALocks X and YWorker B1. Acquire X2. Acquire Y3. Wait for Y while keeping X4. Wait for X while keeping Y
The circular-wait trap. A owns X and requests Y while B owns Y and requests X; neither releases what the other needs.Scroll horizontally to read the full diagram on a small screen.
Encode a consistent acquisition order python
from contextlib import ExitStack
from threading import Lock
locks = {"account-a": Lock(), "account-b": Lock()}
keys = ["account-b", "account-a"]
with ExitStack() as stack:
    for key in sorted(set(keys)):
        stack.enter_context(locks[key])
    print("both locks acquired in canonical order")
Expected result
both locks acquired in canonical order

Go deeper: [21] Python 3.11 threading reference · [3] MIT 6.S081 Operating System Engineering, Fall 2020 video schedule

A timeout is evidence, not a complete repair

A global lock order can remove cycles when every relevant participant follows the same rule. Use stable resource identifiers and handle the case where two logical names refer to the same lock; acquiring a non-reentrant lock twice can deadlock one thread against itself. The example removes duplicate keys before ordering. In a real design, consider whether a single owner or message-passing boundary would make the invariant simpler than coordinating several locks.

Starvation differs from deadlock: a system can keep doing useful work while one task never receives enough access to finish. Livelock differs again: tasks actively react to one another but fail to make useful progress, such as repeatedly abandoning and retrying at the same time. Fairness policies, bounded retries, randomized backoff, and reduced contention address different aspects. Name the observed failure rather than calling every wait a deadlock.

Lock-acquisition timeouts can help detect or escape a wait, but the caller must know how to leave state consistent. An expired timeout does not automatically roll back arbitrary earlier writes. If a transfer partly changed state before waiting for another resource, simply returning an error may be incorrect. Acquire the needed protection before the mutation when possible, keep transitions atomic at the right boundary, and design recovery explicitly.

Go deeper: [21] Python 3.11 threading reference · [23] Python 3.11 concurrent.futures reference

Keep these ideas

  • Safety and liveness need separate arguments.
  • Consistent resource ordering only works when every participant follows it.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

10.1 · Practice task

Two workers acquire A then B in one code path, and B then A in another. What design change prevents that two-lock cycle?

Hint: All participants must agree on one order.

Read the worked solution

10.2 · Practice task

A worker repeatedly loses access while others finish tasks. Is that necessarily deadlock?

Hint: Ask whether the system as a whole is still progressing.

Read the worked solution

Chapter 11

Understand files, names, descriptors, and permissions

Follow the handle your program uses instead of treating a path as the file itself.

By the end of this chapter
  • Distinguish pathname, descriptor, and open-file state
  • Explain close, offsets, and permission boundaries

A path names an object through a namespace

A pathname is interpreted through directories and the process’s filesystem context. A file descriptor is a small process-local integer referring to an open resource under Unix-like interfaces. The descriptor is not the filename or the disk block address. After opening a file, operations use the handle and associated open-file state. Renaming a path and changing an already open handle are therefore not the same event. This distinction explains many log-rotation and temporary-file surprises.

An open-file description can hold state such as the current offset and access mode. Duplicated descriptors can share that underlying offset, so reading through one descriptor can affect where another shared reference reads next. Distinct opens may have independent offset state even for the same file. Avoid building a correctness argument around the numeric descriptor value itself: a closed number can be reused later for a different resource.

Two opens have separate positions python
from pathlib import Path
from tempfile import TemporaryDirectory
with TemporaryDirectory() as directory:
    path = Path(directory) / "notes.txt"
    path.write_text("ABCDE", encoding="ascii")
    with path.open("r", encoding="ascii") as first, \
         path.open("r", encoding="ascii") as second:
        print(first.read(2))
        print(second.read(1))
        print(first.read(1))
Expected result
AB
A
C
A path lookup produces a usable handleThe process resolves a name and checks access to obtain a descriptor, which refers to open-file state and the underlying file object.PathnameA name resolved through directoriesOpen operationResolve, check, and create handle stateDescriptorProcess-local reference used by read/writeUnderlying fileData and filesystem metadata
A path lookup produces a usable handle. The process resolves a name and checks access to obtain a descriptor, which refers to open-file state and the underlying file object.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [11] Linux open manual · [12] Linux dup manual · [19] Python 3.11 operating-system interfaces

Ownership and cleanup are part of correctness

A context manager closes a Python file on normal exit and exceptions. Closing releases that handle; it does not mean all possible references to the underlying file disappeared or that every data update is durable on storage. Resource leaks occur when handles accumulate beyond the application’s intended lifetime. A service that leaks one descriptor per request can fail long before it runs out of memory, even when each request’s text processing is correct.

Unix-style permission bits distinguish read, write, and execute/search capabilities for owner, group, and others, with additional mechanisms such as ACLs and platform policies possible. Directory search permission is important for reaching a named entry; a file’s mode alone does not describe every path-access condition. Check the actual API error and context. A permission failure should not be "fixed" by broadly opening every file to all users.

TermWhat it describesCommon mistake
PathnameA route through a namespaceTreating it as a permanent object identity
DescriptorA process-local open referenceAssuming its integer is globally unique
CloseRelease this open referenceAssuming it guarantees storage durability

For temporary work, create a dedicated temporary directory with a managed lifetime, write only the exercise’s own files, and let the context remove them. Keep output paths separate from secrets and source configuration. If a program needs atomic publication or crash durability, use the next chapter’s stronger concepts rather than assuming that a successful write call solves every persistence problem.

Go deeper: [13] Linux pathname resolution · [25] Python 3.11 tempfile reference · [14] Linux fsync manual

Keep these ideas

  • A pathname, an open handle, and stored data are distinct layers.
  • Resource lifetime and least privilege matter in ordinary file code.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

11.1 · Practice task

A service closes descriptor 7, then a later open returns descriptor 7. Is it necessarily the same file?

Hint: Descriptor integers are reusable within a process.

Read the worked solution

11.2 · Practice task

Why can a file with permissive read bits still be inaccessible through a pathname?

Hint: The path crosses directories and can be subject to other policy.

Read the worked solution

Chapter 12

Reason about writes, atomic replacement, and crashes

Define what survives before using the word "saved".

By the end of this chapter
  • Distinguish buffered writes from durability
  • Explain a carefully scoped temporary-file replacement pattern

There are several meanings of "written"

A language-level write may copy bytes into a runtime buffer. Flushing that buffer passes work toward the operating system, but the kernel and storage hardware can still have pending work. A successful system write can report acceptance of bytes without proving survival of a sudden crash. Durability is a stronger property with documented synchronization requirements and hardware assumptions. If an application tells a learner that progress is saved permanently, it should know which boundary has actually acknowledged the state.

Filesystems organize persistent names, metadata, and data blocks. Updating a file can require multiple lower-level changes. A crash between those changes is why journaling, copy-on-write designs, ordering constraints, and recovery procedures exist. These mechanisms have different guarantees. Do not infer that the presence of a journal makes every recent user-data write durable. A filesystem’s consistency after recovery and an application’s latest committed state are related but different questions.

Persistence has several acknowledgment boundariesData moves through a user buffer, kernel cache, storage path, and durable medium; a successful earlier boundary does not automatically imply the later ones.Runtime bufferThe language may retain pending bytesKernel cacheThe OS tracks dirty data and metadataStorage pathControllers and devices perform requested workDurable stateSurvival depends on synchronization and hardware guarantees
Persistence has several acknowledgment boundaries. Data moves through a user buffer, kernel cache, storage path, and durable medium; a successful earlier boundary does not automatically imply the later ones.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [14] Linux fsync manual · [1] Operating Systems: Three Easy Pieces, version 1.10

Publish a complete file instead of exposing half a rewrite

A local atomic-replacement teaching pattern python
import json
import os
from pathlib import Path
from tempfile import TemporaryDirectory

with TemporaryDirectory() as directory:
    target = Path(directory) / "progress.json"
    temporary = Path(directory) / "progress.tmp"
    with temporary.open("w", encoding="utf-8") as stream:
        json.dump({"lessons": 3}, stream)
        stream.flush()
        os.fsync(stream.fileno())
    os.replace(temporary, target)
    print(json.loads(target.read_text(encoding="utf-8")))
Expected result
{'lessons': 3}

Writing a temporary file in the same directory and then replacing the target can let concurrent readers see a complete old or complete new name binding rather than a partially rewritten target, under the platform’s documented replacement semantics. The example is not a universal crash-durability guarantee. On relevant Unix/Linux filesystems, persisting the containing directory can be necessary for the renamed entry to survive a crash; filesystem, mount, storage, and platform behavior must be checked. Cross-filesystem replacement is a different case.

A robust application also handles synchronization errors, permissions, storage exhaustion, interrupted work, and temporary-file cleanup. It must define whether an error means the old version is certainly retained, the new version is published, or the outcome needs reconciliation. Backups and checksums can detect or recover from additional failures, but they also need a tested restore path. For a real multi-record transactional workload, an appropriate database is often safer than inventing a storage protocol from this introductory example.

Go deeper: [19] Python 3.11 operating-system interfaces · [14] Linux fsync manual · [15] Linux rename manual

Keep these ideas

  • Buffered, published, consistent, and durable are different claims.
  • Test recovery and document platform-specific persistence guarantees.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

12.1 · Practice task

Does calling stream.flush() alone guarantee survival of sudden power loss?

Hint: Identify which buffer that method controls.

Read the worked solution

12.2 · Practice task

Why keep the temporary file in the target’s directory for the replacement pattern?

Hint: Think about filesystem boundaries and publication semantics.

Read the worked solution

Chapter 13

Connect I/O, event loops, containers, and resource limits

See which mechanism changes the view of resources and which controls consumption.

By the end of this chapter
  • Distinguish blocking I/O, readiness, and asynchronous completion
  • Separate namespaces, limits, virtual machines, and security claims

Waiting can be organized in several ways

A blocking I/O call can put the calling thread to sleep until progress or an error is available. Nonblocking I/O returns promptly when the operation cannot currently proceed. Readiness interfaces let an application monitor several handles and learn which may support I/O now. Completion-based interfaces report that submitted work completed. These are related tools, not synonyms. A readiness event does not mean an entire application message is present or that any amount of requested I/O will finish without further waiting.

An event loop coordinates many state machines on a small number of threads. Each operation must make bounded progress and yield control rather than performing an unrelated long blocking call in the loop. Otherwise one slow action stalls all the work sharing that loop. Linux epoll, BSD/macOS kqueue, and Windows completion facilities differ in API and semantics. A portable library can select an appropriate backend, but your application still needs correct framing, cancellation, and resource limits.

Ask which readiness selector the host chooses python
import selectors
with selectors.DefaultSelector() as selector:
    print(type(selector).__name__)
Expected result
Typical: KqueueSelector on macOS or EpollSelector on Linux; platform and build may differ.
An event loop is coordination, not magic parallelismThe loop waits for relevant events, runs a bounded callback, updates state, and returns to waiting while other work remains eligible.Wait for eventsAsk the OS about registered handlesRun a bounded stepRead or write what is availableUpdate application stateAdvance a parser or complete a requestReturn to the loopAllow other ready work to progress
An event loop is coordination, not magic parallelism. The loop waits for relevant events, runs a bounded callback, updates state, and returns to waiting while other work remains eligible.Scroll horizontally to read the full diagram on a small screen.

Go deeper: [24] Python 3.11 selectors reference · [16] Linux epoll manual

A different resource view is not unlimited isolation

A virtual machine presents virtualized hardware to a guest operating system. A container commonly packages processes using host-kernel isolation mechanisms and resource controls. Linux namespaces can give a process a different view of resources such as process IDs, mounts, or networking. Control groups can account for and limit resource use. Neither mechanism alone establishes every security property. Containers share important host-kernel machinery, and configuration, privileges, mounts, and kernel vulnerabilities affect the actual boundary.

Resource limits improve predictability only when aligned with the workload. A memory cap can turn excessive allocation into a process failure rather than a host-wide shortage, but the application must recover or report failure appropriately. CPU quotas can create throttling that looks like unexplained latency. Descriptor limits can stop new connections. Observe the resource that is constrained instead of assuming that a host with idle-looking CPU must give every container unrestricted execution.

MechanismMain teaching purposeDoes not imply
NamespaceA scoped view of a resourceA complete independent kernel
Control groupResource accounting and controlCorrect application authorization
Virtual machineA guest OS on virtualized hardwareImmunity to every shared-host risk

For this guide, inspect concepts and use safe local processes; do not change system-wide limits or kernel settings to follow a chapter. Advanced container labs should state the runtime, privileges, host OS, and cleanup steps. On macOS, a Linux container runtime commonly involves a Linux virtual machine, so a Linux-specific observation inside a container is not evidence that the macOS kernel implements the same interface directly.

Go deeper: [17] Linux namespaces overview · [18] Linux cgroup v2 documentation · [9] Linux virtual-memory concepts

Keep these ideas

  • Choose I/O semantics deliberately and keep event-loop steps bounded.
  • A resource view, a resource limit, and a security boundary are different claims.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

13.1 · Practice task

An event loop receives a socket-readiness notification. Can it assume one complete JSON message is ready?

Hint: Readiness concerns I/O progress, while JSON boundaries are application framing.

Read the worked solution

13.2 · Practice task

A container shows low CPU usage but high response latency. Why is "the host has spare cores" insufficient as a diagnosis?

Hint: The workload may be throttled, blocked, or limited elsewhere.

Read the worked solution

Chapter 14

Capstone: a bounded file-analysis worker

Combine ownership, concurrency, cleanup, measurement, and a precise result contract.

By the end of this chapter
  • Build a reproducible local worker with bounded inputs
  • Explain failure handling and distinguish measurements from guarantees

Define useful work and its limits

Build a local tool that counts words in a small, explicit set of UTF-8 text files. The input is a list of paths chosen by the learner, not a recursive scan of the whole computer. Limit the example to a small number of files and a maximum size per file. Each result contains either a count or a clear failure category. A missing file, invalid UTF-8, and a worker exception are not silently converted into a count of zero, because zero is a valid observation for an empty file.

Begin with a pure function that counts words in a supplied string, then add file access with context-managed lifetime. Only after those pieces work should you introduce a bounded worker pool. Keep the concurrency level small and measure before increasing it. File I/O can overlap, but the storage device, page cache, Python runtime, and workload size determine whether concurrency helps. A cached second run should not be compared with an uncached first run as if worker count were the only difference.

A small explicit worker pool with safe temporary inputs python
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
from tempfile import TemporaryDirectory

def count_file(path):
    if path.stat().st_size > 4096:
        raise ValueError("teaching input exceeds size limit")
    with path.open(encoding="utf-8") as stream:
        return len(stream.read(4097).split())

with TemporaryDirectory() as directory:
    paths = [Path(directory) / name for name in ("a.txt", "b.txt")]
    paths[0].write_text("learn operating systems", encoding="utf-8")
    paths[1].write_text("read and practise", encoding="utf-8")
    with ThreadPoolExecutor(max_workers=2) as pool:
        results = list(pool.map(count_file, paths))
    print(results)
Expected result
[3, 3]

The size check is appropriate only for these controlled temporary files. For files that other processes can change concurrently, a stat-before-read check has a race: the file can grow after the check. A robust implementation reads a bounded byte sequence, detects overflow, and decodes according to the contract, or uses another explicit snapshot mechanism. That limitation is useful to discover rather than hide. File names and earlier metadata observations do not freeze a file’s future contents.

Go deeper: [23] Python 3.11 concurrent.futures reference · [25] Python 3.11 tempfile reference · [19] Python 3.11 operating-system interfaces

Turn the demonstration into an experiment

A bounded work pipelineAn explicit input set enters a small worker pool. Each worker owns its file handle, reports a count or failure, and the caller collects results before cleanup.Input contractExplicit files, format, size, and count boundsBounded workersA small known concurrency levelPer-task ownershipOpen, read, validate, and close one fileCollect and clean upReport results and wait for workers before removing temporary data
A bounded work pipeline. An explicit input set enters a small worker pool. Each worker owns its file handle, reports a count or failure, and the caller collects results before cleanup.Scroll horizontally to read the full diagram on a small screen.

Add tests for an empty file, one word, multiple whitespace characters, non-ASCII text, a missing path, invalid encoding, and a too-large input. Make the failure cases observable in returned results or structured exceptions. Verify that the executor is shut down and temporary files can be removed after both success and failure. Do not use an infinite task source with an API that eagerly collects all inputs. The queue or submission strategy must bound pending work as well as the number of running workers.

Measure wall-clock duration using a monotonic performance counter and record file sizes, worker count, runtime, operating system, and whether repeated reads benefit from cache. If two workers are slower for tiny files, explain startup and coordination costs before declaring the operating system broken. The report should include an ownership diagram, acceptance tests, a failure table, and a paragraph stating what remains outside scope: hostile path races, durable database transactions, full sandboxing, and production-grade cancellation.

Go deeper: [23] Python 3.11 concurrent.futures reference · [28] Python 3.11 time reference · [22] Python 3.11 queue reference

Keep these ideas

  • Bound running work, pending work, input size, and output size separately.
  • A reproducible experiment states both its guarantees and its limitations.

Practise before moving on

Try each task before opening the solution. Explain your reasoning, including a boundary or failure case.

14.1 · Practice task

Replace the controlled-file size check with a bounded-read contract suitable for a file that might grow. What should happen after the bound is exceeded?

Hint: Read at most limit plus one byte before decoding or counting.

Read the worked solution

14.2 · Practice task

Why can two workers fail to improve the running time of this capstone?

Hint: Parallel execution is only one part of elapsed time.

Read the worked solution

Practice with feedback

Worked solutions

These solutions show a valid line of reasoning. Compare assumptions and intermediate steps, rather than only the final number or output. Other implementations can be equally good when they preserve the stated contract.

Chapter 1 · Meet the operating system without memorizing a list

Solution 1.1

The language runtime or standard-I/O library can buffer output and combine it with later writes. The kernel can buffer or queue work further. A visible language call is not a one-to-one trace of device operations. To investigate timing, identify buffering layers and use documented flush or synchronization behavior rather than assuming the source line is a physical event.

Return to the task

Solution 1.2

No. The address space can include unmapped gaps, shared mappings, reserved ranges, and pages not currently resident. Virtual size and resident memory measure different things. Interpret the specific operating system’s metrics and workload before concluding there is a leak or a shortage of physical memory.

Return to the task

Chapter 2 · Create, run, wait for, and clean up processes

Solution 2.1

No. On success, the process runs the replacement program. An exec-family call returns to the old code only when it fails, with an error indication appropriate to the API. The PID can remain the same even though the program and address space changed, which is why process identity and program filename are not interchangeable.

Return to the task

Solution 2.2

Each child consumes scheduling capacity, memory, descriptors, and management overhead. Unlimited creation can exhaust the host or create severe queueing. Use a bounded worker model, admission policy, per-task limits, and a collection/cleanup path. A fast spawn benchmark does not show that unbounded process creation is operationally safe.

Return to the task

Chapter 3 · Understand threads, states, and context switching

Solution 3.1

Yes. The scheduler can interleave execution, and one task can use CPU time while the other waits for I/O. That is concurrency. Actual simultaneous CPU execution requires suitable parallel hardware and runtime support. Distinguishing the two avoids claiming that adding threads necessarily halves computation time.

Return to the task

Solution 3.2

The scheduler can run either worker first, so the queue may receive 4 then 9 or 9 then 4. Sorting makes the displayed output deterministic because order is irrelevant to this calculation. If order had business meaning, the program would need explicit sequence identifiers or another ordering rule rather than silently sorting it away.

Return to the task

Chapter 4 · Calculate scheduling tradeoffs with small timelines

Solution 4.1

A-then-B completes at 6 and 8, so mean turnaround is 7. B-then-A completes at 2 and 8, so mean turnaround is 5. Total CPU work remains 8 in both. This shows how completion experience can improve without making the processor execute the underlying work faster.

Return to the task

Solution 4.2

More slices mean more scheduling and context-switch overhead, and tasks can lose cache or translation locality. A smaller quantum may still improve interactive responsiveness. The right tradeoff depends on workload and objectives; measure both responsiveness and overhead rather than optimizing one number in isolation.

Return to the task

Chapter 5 · Build a useful model of virtual memory

Solution 5.1

No. The same virtual address can map to different physical pages in different processes. Intentional shared mappings are possible, but numeric equality alone does not establish them. You need evidence about the mapping and its permissions, not just a printed address.

Return to the task

Solution 5.2

The object may still have references, the runtime allocator may keep freed memory for future allocations, shared/cached pages may remain accounted, or reclamation may be delayed by implementation details. Check actual object lifetime and repeated-workload behavior. A single resident-memory observation does not identify the cause.

Return to the task

Chapter 6 · Translate addresses and explain page faults

Solution 6.1

The offset is 2,500 − 2×1,024 = 452. The physical address is 7×1,024 + 452 = 7,620. The virtual page number changes into a frame number while the offset stays the same. This arithmetic assumes that the mapping exists and the requested access is permitted.

Return to the task

Solution 6.2

No. The processor or system can obtain the valid mapping from page-table information and continue without reading the page from storage. A TLB miss can cost time, but it is not equivalent to a major page fault. Determine which event a performance counter actually measures before interpreting it.

Return to the task

Chapter 7 · Use locality to reason about caches and memory pressure

Solution 7.1

A misses, B misses, A hits and becomes recent, C misses and evicts B, and B misses and evicts A. There are four misses. State both the policy and capacity; changing either can change the result. The trace is small enough to verify by drawing the two frame slots after every access.

Return to the task

Solution 7.2

Additional workers may increase memory pressure, reclaim, page faults, and I/O while adding scheduling overhead. The machine spends more effort moving or waiting for data. Measure useful completion rate and memory-related stalls while varying concurrency. More runnable work is not the same thing as more productive work.

Return to the task

Chapter 8 · Protect shared state with an explicit invariant

Solution 8.1

The invariant spans both balances. Another participant can observe money removed from A before it appears in B, or concurrent transfers can interfere with validation. Protect the full state transition using one appropriate lock or a carefully ordered multi-lock protocol, and ensure all relevant readers follow that protocol. Database transactions are often the appropriate boundary for persistent account data.

Return to the task

Solution 8.2

The scheduler may not trigger the harmful timing during that run, the runtime may temporarily serialize operations, or the workload may be too small. A proof relies on the language/runtime guarantees and synchronization design. Use deterministic interleaving models to explain failures and stress tools as additional evidence, not as a substitute for an invariant.

Return to the task

Chapter 9 · Wait for a condition without wasting a CPU

Solution 9.1

After waking, the predicate may still be false because another worker consumed the resource or the API allowed a spurious wakeup. The worker must reacquire the lock and recheck the shared condition. Proceeding after one notification without rechecking can read nonexistent work or violate a bound.

Return to the task

Solution 9.2

The unfinished-task count remains positive, so join can wait indefinitely even after the visible queue is empty. Put task_done in a finally block paired with each successful get, and test exceptional paths. Empty does not imply all retrieved work has been completed.

Return to the task

Chapter 10 · Recognize deadlock, starvation, and unsafe lock ordering

Solution 10.1

Choose a canonical total order on the resource identities and acquire the distinct needed locks in that order in every path. Release them reliably. The guarantee depends on complete adoption: one exceptional path using the opposite order can reintroduce the cycle. A single owner or a larger transaction boundary may be clearer than many independent locks.

Return to the task

Solution 10.2

No. It may be starvation: other tasks make progress while this one is continually delayed. A deadlock involves a set unable to make required progress because of a wait cycle or equivalent dependency. Diagnose contention, scheduling, and fairness before applying a deadlock remedy that does not address the actual failure.

Return to the task

Chapter 11 · Understand files, names, descriptors, and permissions

Solution 11.1

No. The operating system can reuse an available descriptor number for a different open resource. Code must track ownership and lifetime rather than using an old integer after close. Such stale-handle bugs can accidentally act on an unrelated file or socket.

Return to the task

Solution 11.2

The process may lack directory search permission on a parent, the path may resolve differently than expected, or ACLs, sandbox rules, mount state, or another access-control mechanism may deny it. Inspect the precise error and path context. Changing only the final file’s mode may not solve the problem and may expose data unnecessarily.

Return to the task

Chapter 12 · Reason about writes, atomic replacement, and crashes

Solution 12.1

No. It flushes the language-level stream buffer toward the underlying operating-system interface. Kernel caches, device caches, ordering, and error handling remain relevant. Stronger durability requires the documented synchronization protocol for the platform and storage stack, and even that depends on its stated hardware assumptions.

Return to the task

Solution 12.2

Using the same directory normally keeps the temporary and target on the same filesystem and supports the intended replacement operation. Replacing across filesystems may fail or require a different copy procedure without the same atomicity. The directory entry itself can need synchronization for crash durability on applicable systems. Check errors rather than silently falling back to an unsafe partial rewrite.

Return to the task

Chapter 13 · Connect I/O, event loops, containers, and resource limits

Solution 13.1

No. Some bytes may be available, EOF may be observable, or the subsequent operation may need careful nonblocking error handling. The parser must accumulate and frame the message according to the protocol and enforce bounds. Readiness does not supply an application-level message contract.

Return to the task

Solution 13.2

A quota can throttle execution, the process may wait on storage or a lock, or a dependency may be slow. Inspect the container’s limits, throttling metrics, blocked states, and stage timings. Available host capacity does not prove that this workload has permission or ability to use it.

Return to the task

Chapter 14 · Capstone: a bounded file-analysis worker

Solution 14.1

Open the file in binary mode, read at most limit+1 bytes, reject if more than limit were obtained, and only then decode according to the declared encoding. This bounds this read’s memory use and avoids trusting earlier size metadata. It does not make the path immune to all races or provide a consistent snapshot of arbitrary concurrent edits; document that remaining limitation.

Return to the task

Solution 14.2

The inputs may be too small, worker setup and coordination may dominate, storage may serialize access, the runtime may limit CPU parallelism, or the second experiment may see different cache state. Measure controlled runs and distinguish CPU time from wall time. The purpose is a correct bounded workflow first, with an evidence-based performance explanation second.

Return to the task

Retrieve before you review

Final knowledge check

Choose one answer for each question and write a short reason. Use the explanation to find the assumption or misconception behind an error.

  1. 1. Which statement about a library call is accurate?

    1. It always corresponds to exactly one device operation
    2. It may run in user space or invoke one or more system calls
    3. It always enters the kernel
    4. It bypasses all permissions
    Check answer and reasoning
  2. 2. On success, what does exec-family program replacement do?

    1. Always creates a second child
    2. Returns to the next old-program statement
    3. Replaces the calling process’s program image
    4. Removes every process on the machine
    Check answer and reasoning
  3. 3. Threads in one process commonly share what?

    1. One identical stack for all threads
    2. Every register value at every instant
    3. No resources at all
    4. An address space and many process resources
    Check answer and reasoning
  4. 4. Two tasks arrive at zero: A needs 5 CPU units, B needs 1. Running B then A gives which mean turnaround?

    1. 3.5 units
    2. 6 units
    3. 1 unit
    4. 5.5 units
    Check answer and reasoning
  5. 5. Two processes use numeric virtual address 0x1000. What follows?

    1. They must share one physical byte
    2. The mappings can point to different physical memory
    3. One must be invalid
    4. Virtual memory is disabled
    Check answer and reasoning
  6. 6. A TLB miss necessarily means what?

    1. A disk read must occur
    2. The program must terminate
    3. The cached translation was not found
    4. The file was deleted
    Check answer and reasoning
  7. 7. With two LRU frames, accesses A, B, A, C produce how many misses?

    1. 1
    2. 2
    3. 4
    4. 3
    Check answer and reasoning
  8. 8. What should determine the scope of a critical section?

    1. The shared-state invariant and the operations needed to preserve it
    2. A random fixed number of lines
    3. Only where printing occurs
    4. The fastest worker’s timing
    Check answer and reasoning
  9. 9. Why recheck a predicate after condition-variable wakeup?

    1. Wakeups reserve all resources forever
    2. The desired state may no longer hold
    3. Locks become unnecessary
    4. The thread must always exit
    Check answer and reasoning
  10. 10. A holds X and waits for Y; B holds Y and waits for X. What is the key issue?

    1. A cache hit
    2. A fast context switch
    3. A circular wait
    4. A valid shutdown signal
    Check answer and reasoning
  11. 11. After a descriptor is closed, its number may be reused for what?

    1. Only the same filename
    2. Only the parent process
    3. Nothing until reboot
    4. A different open resource
    Check answer and reasoning
  12. 12. Which statement about stream.flush() is accurate?

    1. It alone does not guarantee power-loss durability
    2. It always synchronizes the containing directory
    3. It bypasses every buffer
    4. It replaces a database transaction
    Check answer and reasoning
  13. 13. What do Linux namespaces primarily supply in this guide’s model?

    1. Unlimited CPU
    2. Scoped views of selected resources
    3. A complete independent guest kernel in every case
    4. Automatic application authorization
    Check answer and reasoning
  14. 14. Why is a stat-before-read size check insufficient for a concurrently changing file?

    1. File contents can never change
    2. Every filesystem ignores stat
    3. The file can grow between the check and the read
    4. Python cannot read files
    Check answer and reasoning

Assessment explanations

1. Answer B

It may run in user space or invoke one or more system calls

A library can compute locally, buffer work, or call several kernel services. Source calls are not a one-to-one device trace.

Revisit the chapter · Return to the question

2. Answer C

Replaces the calling process’s program image

The calling process runs the replacement program. Returning to the old image is the failure path, not the normal success path.

Revisit the chapter · Return to the question

3. Answer D

An address space and many process resources

Threads have distinct execution contexts and stacks but commonly share memory and many process resources, making synchronization necessary.

Revisit the chapter · Return to the question

4. Answer A

3.5 units

B finishes at 1 and A at 6, so mean turnaround is (1+6)/2 = 3.5 under the stated no-I/O, no-switch-cost model.

Revisit the chapter · Return to the question

5. Answer B

The mappings can point to different physical memory

Translation is interpreted within the address-space context. Numeric equality does not establish physical sharing.

Revisit the chapter · Return to the question

6. Answer C

The cached translation was not found

A page-table lookup may find a valid resident mapping without storage I/O. TLB misses and page faults are distinct.

Revisit the chapter · Return to the question

7. Answer D

3

A and B miss, A hits and becomes recent, then C misses and evicts B. The result depends on this exact trace and capacity.

Revisit the chapter · Return to the question

8. Answer A

The shared-state invariant and the operations needed to preserve it

The protected transition must preserve the invariant for all participants. Locking one convenient assignment may be insufficient.

Revisit the chapter · Return to the question

9. Answer B

The desired state may no longer hold

Another worker can consume the resource, and APIs can permit spurious wakeups. Waking means recheck while holding the appropriate lock.

Revisit the chapter · Return to the question

10. Answer C

A circular wait

Each participant waits for a resource held by the other. Consistent acquisition order can prevent this modeled cycle when universally followed.

Revisit the chapter · Return to the question

11. Answer D

A different open resource

Descriptor integers are process-local reusable handles. Ownership and lifetime must be tracked rather than inferred from the number.

Revisit the chapter · Return to the question

12. Answer A

It alone does not guarantee power-loss durability

Flushing a language buffer is weaker than the full documented storage synchronization and crash-recovery protocol.

Revisit the chapter · Return to the question

13. Answer B

Scoped views of selected resources

Namespaces change resource views. Resource limits and application permissions are separate responsibilities.

Revisit the chapter · Return to the question

14. Answer C

The file can grow between the check and the read

The observation can become stale before use. A bounded read with overflow detection enforces a clearer memory bound, while other race and snapshot concerns still need explicit treatment.

Revisit the chapter · Return to the question

Glossary

Backpressure
Slowing or blocking producers when downstream capacity is exhausted. Chapter
Blocked state
A state waiting for an event rather than currently eligible CPU execution. Chapter
Concurrency
Overlapping progress of multiple activities across time. Chapter
Condition variable
A waiting mechanism coordinated with a lock and shared-state predicate. Chapter
Context switch
Saving and restoring execution state to change the running activity. Chapter
Control group
A Linux mechanism for hierarchical resource accounting and control. Chapter
Critical section
A protected state transition whose coordination preserves an invariant. Chapter
Deadlock
A dependency state preventing required progress among waiting activities. Chapter
Durability
The promised survival of acknowledged state across specified failures. Chapter
exec
A family of operations replacing the calling process’s program image. Chapter
File descriptor
A process-local integer handle referring to an open resource. Chapter
fork
A Unix-like process-creation operation duplicating a caller’s process context under defined rules. Chapter
Invariant
A condition that must remain true at the boundaries visible to other participants. Chapter
Kernel
The privileged core managing protected operations and shared machine resources. Chapter
Livelock
Ongoing activity that fails to produce useful progress because of repeated reactions. Chapter
Locality
A tendency to reuse recent or nearby data, useful to caching. Chapter
LRU
Least-recently-used replacement, evicting the item unused for the longest recent interval in the model. Chapter
Namespace
A scoped view of selected operating-system resources. Chapter
Page
A fixed-size unit of a virtual-memory mapping. Chapter
Page fault
An exceptional memory-access condition requiring system handling. Chapter
Page frame
A physical-memory slot that can back a virtual page. Chapter
Page table
Translation and protection information mapping virtual pages. Chapter
Parallelism
Simultaneous execution on multiple execution resources. Chapter
PID
A process identifier meaningful within an operating-system or namespace context. Chapter
Process
A running instance with an address space, execution state, and resources. Chapter
Program
Stored instructions and data that can be loaded for execution. Chapter
Quantum
A scheduling time slice in a policy such as round-robin. Chapter
Race condition
An incorrect dependence of an outcome on timing or ordering. Chapter
Readiness
An indication that an I/O operation may currently make progress under its API rules. Chapter
Resident memory
Memory currently present in physical RAM under the platform’s accounting rules. Chapter
Response time
Delay from arrival until a task first receives service in the stated model. Chapter
Starvation
Continued denial of useful progress to one task while others may advance. Chapter
System call
A controlled interface through which a program requests kernel work. Chapter
Thread
An execution context within a process, commonly sharing its address space. Chapter
TLB
A cache of address-translation information. Chapter
Turnaround time
Completion time minus arrival time for a task. Chapter
User space
The less-privileged execution environment for ordinary applications and libraries. Chapter
Virtual address
An address interpreted through a process’s mappings and protection context. Chapter
Working set
The actively needed data over a chosen interval. Chapter
Zombie
A terminated Unix child whose termination record has not yet been collected. Chapter

Read and watch with a purpose

Reading and video library

Use the chapter source links to choose a relevant next explanation. Each entry below states what it adds. Documentation links may evolve; edition 2026.12 records the assumptions used here.

  1. Operating Systems: Three Easy Pieces, version 1.10

    Remzi and Andrea Arpaci-Dusseau, University of Wisconsin–Madison · book

    Author-hosted chapter reading on virtualization, concurrency, persistence, and security. Link to the authorized chapters; do not mirror their text or figures.

    https://pages.cs.wisc.edu/~remzi/OSTEP/
  2. MIT xv6 RISC-V teaching operating system, 2024 course page

    MIT PDOS · book

    Readable teaching kernel and author-hosted book; not a description of every production kernel.

    https://pdos.csail.mit.edu/6.1810/2024/xv6.html
  3. MIT 6.S081 Operating System Engineering, Fall 2020 video schedule

    MIT PDOS · Watch / course

    Official lecture schedule with actual video links for processes, page tables, locking, scheduling, and filesystems. The archived course has its own edition.

    https://pdos.csail.mit.edu/6.S081/2020/schedule.html
  4. Linux fork manual

    Linux man-pages project · docs

    Process creation and inherited-state details for Linux; portability boundaries are documented.

    https://man7.org/linux/man-pages/man2/fork.2.html
  5. Linux execve manual

    Linux man-pages project · docs

    Program-image replacement and error behavior.

    https://man7.org/linux/man-pages/man2/execve.2.html
  6. Linux wait manual

    Linux man-pages project · docs

    Collecting child state and understanding zombie records.

    https://man7.org/linux/man-pages/man2/wait.2.html
  7. Linux scheduling overview

    Linux man-pages project · docs

    Scheduling interfaces and policy classes. Implementation descriptions can lag changes; check kernel-specific documentation.

    https://man7.org/linux/man-pages/man7/sched.7.html
  8. Linux scheduler documentation

    Linux kernel project · docs

    Implementation-specific scheduling material; consult the version matching the kernel under study.

    https://www.kernel.org/doc/html/latest/scheduler/index.html
  9. Linux virtual-memory concepts

    Linux kernel project · docs

    Virtual memory, pages, TLBs, reclaim, and page-cache concepts for MMU-equipped systems.

    https://www.kernel.org/doc/html/latest/admin-guide/mm/concepts.html
  10. Linux mmap manual

    Linux man-pages project · docs

    Mapped memory, sharing modes, and access permissions.

    https://man7.org/linux/man-pages/man2/mmap.2.html
  11. Linux open manual

    Linux man-pages project · docs

    Descriptors, open-file descriptions, modes, and error handling.

    https://man7.org/linux/man-pages/man2/open.2.html
  12. Linux dup manual

    Linux man-pages project · docs

    Duplicated descriptors and shared offset state.

    https://man7.org/linux/man-pages/man2/dup.2.html
  13. Linux pathname resolution

    Linux man-pages project · docs

    Directory traversal, search permissions, and path interpretation.

    https://man7.org/linux/man-pages/man7/path_resolution.7.html
  14. Linux fsync manual

    Linux man-pages project · docs

    Synchronization semantics and the separate directory-entry durability issue.

    https://man7.org/linux/man-pages/man2/fsync.2.html
  15. Linux rename manual

    Linux man-pages project · docs

    Atomic namespace replacement conditions and limitations.

    https://man7.org/linux/man-pages/man2/rename.2.html
  16. Linux epoll manual

    Linux man-pages project · docs

    Readiness notification and edge/level behavior; Linux-specific.

    https://man7.org/linux/man-pages/man7/epoll.7.html
  17. Linux namespaces overview

    Linux man-pages project · docs

    Resource-view isolation mechanisms used in container designs.

    https://man7.org/linux/man-pages/man7/namespaces.7.html
  18. Linux cgroup v2 documentation

    Linux kernel project · docs

    Resource accounting, hierarchy, and controller semantics.

    https://www.kernel.org/doc/html/latest/admin-guide/cgroup-v2.html
  19. Python 3.11 operating-system interfaces

    Python Software Foundation · docs

    Portable wrappers and explicitly platform-dependent operations.

    https://docs.python.org/3.11/library/os.html
  20. Python 3.11 subprocess reference

    Python Software Foundation · docs

    Child creation, argument handling, timeouts, output collection, and return codes.

    https://docs.python.org/3.11/library/subprocess.html
  21. Python 3.11 threading reference

    Python Software Foundation · docs

    Threads, locks, condition variables, joining, and CPython 3.11 runtime qualifications.

    https://docs.python.org/3.11/library/threading.html
  22. Python 3.11 queue reference

    Python Software Foundation · docs

    Bounded queues, synchronization, and unfinished-task bookkeeping.

    https://docs.python.org/3.11/library/queue.html
  23. Python 3.11 concurrent.futures reference

    Python Software Foundation · docs

    Executor lifetime, task results, and deadlock cautions.

    https://docs.python.org/3.11/library/concurrent.futures.html
  24. Python 3.11 selectors reference

    Python Software Foundation · docs

    Portable readiness selection over host-specific backends.

    https://docs.python.org/3.11/library/selectors.html
  25. Python 3.11 tempfile reference

    Python Software Foundation · docs

    Managed temporary file and directory lifetimes.

    https://docs.python.org/3.11/library/tempfile.html
  26. Python 3.11 memoryview documentation

    Python Software Foundation · docs

    Buffer views and Python-level shared buffer behavior.

    https://docs.python.org/3.11/library/stdtypes.html#memory-views
  27. Python 3.11 collections reference

    Python Software Foundation · docs

    Ordered dictionaries used in the explicit LRU teaching model.

    https://docs.python.org/3.11/library/collections.html#collections.OrderedDict
  28. Python 3.11 time reference

    Python Software Foundation · docs

    Monotonic and performance-counter clocks for measurements.

    https://docs.python.org/3.11/library/time.html

Continue on OpenLearning

Use the subject library to move between reading, practice, study material, and the wider topic map.

Make the explanation better

If a paragraph needs a clearer example, a command changes, or a diagram hides an important assumption, propose a correction in the open-source repository. Explain the issue and add a source or a reproducible example.

Editable book sources on GitHub

Original OpenLearning instructional text and diagrams: CC BY-SA 4.0. Original code: MIT. External material retains its own copyright and license. This book links to authorized resources; it does not relicense them.