Programming Paradigms · Session 7 · Multi-threading

Why study this

Multi-threading is the model of computation in which several threads of control execute in one address space and communicate by reading and writing the same memory.

The central challenge of writing a correct multi-threaded program can be stated in one sentence: the outcome of a run depends on the interleaving of the threads' instructions, which the scheduler chooses and the program does not control. This is the interleaving model; the session assumes it at the start and shows at the end that each language guarantees it only for programs without data races. A correctness argument must therefore cover every interleaving, and the bugs are subtle and can be costly.

The three ways of coordination

This session presents the three ways in which such an argument is made, each a coordination mechanism: mutual exclusion, atomic instructions with retry, and independence of the order. For each it examines what it guarantees, what it requires of the programmer, and who, if anyone, verifies that requirement.

  1. Mutual exclusion. A lock lets one thread at a time run the code that touches the shared state; the harmful interleavings are forbidden.
  2. Atomic instruction with retry. The operation writes its result with one instruction, compare-and-set, which succeeds only if the value is still the one the operation read, and starts again otherwise; interference is detected by its effect, and the operation is redone.
  3. Independence of the order. The threads share no mutable state while they run, and their results are combined by an operation whose result does not depend on how the parts are grouped, nor, where the parts may arrive in any order, on that order; the interleavings are irrelevant.

Programming language support for concurrency

Threaded concurrency is the model of operating system kernels and database engines, of the runtimes of Java, Go, OCaml 5 and Rust, and, since 2025, of Python without its global lock. OCaml acquired parallel threads in December 2022. Python, whose interpreter lock had for decades prevented its threads from executing Python code concurrently, began in October 2025 to support execution without it. Java, the language of the lab, offers all three ways.

Support and verification, by language

JavaAll three ways · no one verifies

The language of the lab, and one that offers all three ways: synchronized and the locks of java.util.concurrent; AtomicInteger.compareAndSet; parallel streams, which are correct when the combining operation is associative and has an identity. The first two, with the memory model, arrived with Java 5 on 30 September 2004, the third with Java 8 on 18 March 2014. No one verifies the obligation of the lock: a read performed outside the lock, concurrent with a write under it, compiles, executes, and constitutes a data race.

OCaml 5All three ways · races bounded

The second language of the lectures. OCaml 5.0.0, released on 16 December 2022, executes domains in parallel; Mutex and Condition provide the lock, Atomic.compare_and_set the instruction. Before it, at most one thread at a time executed OCaml code. Its memory model carries a proved guarantee: the effect of a data race is bounded in space and in time, so that a racy program may compute a wrong value but cannot crash.

GoA tool verifies, at run time

Go retains the lock and the atomic instruction and adds a tool: the race detector, built on ThreadSanitizer and part of Go since version 1.1 in 2013, reports two unordered accesses that the run made, even when the run's timing kept them apart and the answer was right; a path the run did not take is not checked. Its memory model guarantees that a program free of data races behaves as if its goroutines were interleaved on a single processor; a race on a map or a slice may corrupt memory.

RustThe compiler verifies

Rust 1.0, released on 15 May 2015, rejects at compile time every program that contains a data race, provided the program is written in safe Rust. The rule is ownership: each value has exactly one owner, and may be shared or mutated but never both at once. The compiler does not check the order in which locks are acquired. Session 12 states the rule.

PythonOne lock, optional since 2025

A single interpreter lock allowed at most one thread at a time to execute Python code. PEP 703 makes the lock optional. Python 3.13, released on 7 October 2024, shipped the free-threaded build as experimental; Python 3.14, released on 7 October 2025, supports it officially, as a separate build. Every question of this session now applies to Python.

Multi-threading is everywhere in AI systems, and three of the connections are exactly this session's material.

Multi-threading and AI

The GPUAtomic instruction with retry

A kernel runs thousands of threads over one memory. The backward pass of PyTorch's FlashAttention backend uses atomic additions by default. An atomic addition needs no retry; it is the second way in its one-instruction case. The order of the additions may vary from run to run, and floating-point addition is not associative, so the result may vary.

TrainingIndependence of the order

Gradients computed by many workers are summed, a parallel fold. Floating-point addition is not associative, so two runs of the same training differ in their last bits: the third way, with its obligation unmet.

Python's lockThe runtime’s lock, now optional

The motivation of PEP 703 is neural-network training in Python, where PyTorch's data loader uses processes rather than threads for parallelism, because the lock lets only one thread at a time execute Python code.

ServingA producer–consumer queue

An inference server batches the requests that arrive concurrently into one GPU call. The queue between the request handlers and the batching loop is the lecture's producer–consumer queue; whether it is bounded is a configuration choice, unbounded by default.

The tokenizerThe compiler verifies

The tokenizer that runs before each prompt is sent to the model has its reference implementation in Rust, the language whose compiler verifies the absence of data races.

Learning objectives

In the session

  1. Predict the output of a short two-threaded program, and justify the prediction by exhibiting an interleaving that produces it.
  2. Classify an operation by the contract it satisfies, atomic by exclusion, atomic without exclusion, or deterministic under every interleaving; state the obligation the contract places on the programmer, the progress risk it entails, and who verifies the obligation.
  3. Distinguish a data race from an atomicity violation, and a safety property from a liveness property; place every conditional wait in a loop; eliminate a deadlock by imposing an order on the locks.
  4. State the guarantee that the memory models of Java, C++, Go, OCaml 5 and Rust have in common, that a program free of data races behaves as some interleaving of its threads, and the condition it carries in C++ and Rust, that atomic accesses use the sequentially consistent ordering; decide whether a given history of push and pop operations is explained by a sequential stack; state the lock-free and wait-free progress conditions; and say why locks and compare-and-set do not compose into one atomic operation while transactions do.
  5. Say when a parallel fold agrees with the sequential one, that the combine is associative with an identity and the parts are combined in order, and when commutativity is needed too; and why the counter's result is the same under every way while the stack's depends on the interleaving.

In the lab

  1. Build a mini ray tracer in Java, in two steps.
    • Warm-up: the three structures the ray tracer needs, each with a contract and a check. A counter, written three ways: with a lock, with an atomic instruction, and with one count per thread. Workers, which start the threads and join them. A bounded buffer, written as a monitor.
    • Quest: the picture, rendered by one worker per processor and joined before it is written; the work handed out through a shared counter; the workers stopped from outside with a flag; and, for every piece of shared state, which of the three ways protects it.

13 October 2026. Each date and claim is linked to its source in the text. Logos are the organizations' GitHub avatars.