Programming Search⌘K

Patterncore

Thread confinement

Also called thread confinement, confinement, stack confinement, thread-confined object.

Thread confinement keeps mutable data reachable from one thread only. No other thread can read or write it, so the data needs no lock. Local variables, UI threads and ownership in Rust use this idea.

Family
concurrency
Intent
Avoid races on mutable data by keeping the data, and every reference to it, confined to a single thread.
Also called
Confinement

Intent

Thread confinement avoids races on reassignable references and mutable data by keeping the references or data confined to a single thread.1 Other threads do not get the ability to read or write them directly.1

Problem

Shared mutable state is the root cause of a race condition.1 A lock makes the access safe, but each access then pays for the lock, and each piece of code that uses the data must remember to take it. Many objects are not thread-safe at all. Most Swing object methods are not thread safe, and invoking them from multiple threads risks thread interference or memory consistency errors.2

Solution

Do not share the mutable state.1 Give each piece of mutable data one owner thread, and make sure that no reference to it is reachable from another thread. There are three common forms:

  • Stack confinement. Local variables are always thread confined: each thread has its own stack, and each invocation of a method has its own private copy of the variable.1 If the variable refers to a mutable object, the object must be confined as well.1
  • Owner thread. One thread owns a set of objects, and other threads send it work. All Swing component methods, except the ones labelled thread safe, must be invoked from the event dispatch thread. Other code schedules tasks on that thread with invokeLater or invokeAndWait.2
  • Transfer of ownership. A thread gives the data to another thread and then stops using it. In Go, shared values are passed around on channels, and only one goroutine has access to the value at any given time.3
thread 1: counts = {}  -- fills counts --+
thread 2: counts = {}  -- fills counts --+--> join --> main thread merges
thread 3: counts = {}  -- fills counts --+     (ownership passes to main)

Example

The example gives each of 4 threads a chunk of 10000 words. Each thread counts words into a local dictionary with no lock. When the threads end, the main thread owns the 4 dictionaries and merges them.

chunks: 4
words counted: 40000
distinct words: 5
count of 'a': 8000

The examples for each language show the same program.

PythonGitHub
import threading

WORDS = ["a", "b", "c", "d", "e"]
chunks = [WORDS * 2000 for _ in range(4)]  # 10000 words in each chunk
results = [None] * len(chunks)


def count(index, chunk):
    counts = {}  # local: only this thread can reach it, so no lock
    for word in chunk:
        counts[word] = counts.get(word, 0) + 1
    results[index] = counts  # hand the finished object over


threads = [threading.Thread(target=count, args=(i, c)) for i, c in enumerate(chunks)]
for t in threads:
    t.start()
for t in threads:
    t.join()  # after join, the main thread owns the results

total = {}
for counts in results:
    for word, n in counts.items():
        total[word] = total.get(word, 0) + n
print("chunks:", len(chunks))
print("words counted:", sum(total.values()))
print("distinct words:", len(total))
print("count of 'a':", total["a"])
Output
chunks: 4
words counted: 40000
distinct words: 5
count of 'a': 8000
  • Verdict: idiom. Each thread fills a local counts dictionary, and join makes the main thread the only owner of the results.
#include <iostream>
#include <map>
#include <string>
#include <thread>
#include <vector>

int main() {
    const std::vector<std::string> words = {"a", "b", "c", "d", "e"};
    const int chunks = 4;
    std::vector<std::map<std::string, int>> results(chunks);
    std::vector<std::thread> threads;
    for (int i = 0; i < chunks; i++) {
        threads.emplace_back([&words, &results, i] {
            std::map<std::string, int> counts; // local: no lock
            for (int r = 0; r < 2000; r++) {
                for (const auto& w : words) counts[w]++;
            }
            results[i] = std::move(counts); // hand the finished object over
        });
    }
    for (auto& t : threads) t.join(); // after join, main owns the results

    std::map<std::string, int> total;
    for (const auto& counts : results) {
        for (const auto& [w, n] : counts) total[w] += n;
    }
    int sum = 0;
    for (const auto& [w, n] : total) sum += n;
    std::cout << "chunks: " << chunks << "\n";
    std::cout << "words counted: " << sum << "\n";
    std::cout << "distinct words: " << total.size() << "\n";
    std::cout << "count of 'a': " << total["a"] << "\n";
}
Output
chunks: 4
words counted: 40000
distinct words: 5
count of 'a': 8000
  • Verdict: idiom. Each thread fills a local std::map and moves it into its own slot of results, and join makes the main thread the only owner.
JavaGitHub
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        String[] words = {"a", "b", "c", "d", "e"};
        int chunks = 4;
        @SuppressWarnings("unchecked")
        Map<String, Integer>[] results = new Map[chunks];
        Thread[] threads = new Thread[chunks];
        for (int i = 0; i < chunks; i++) {
            final int index = i;
            threads[i] = new Thread(() -> {
                Map<String, Integer> counts = new HashMap<>(); // local: no lock
                for (int r = 0; r < 2000; r++) {
                    for (String w : words) counts.merge(w, 1, Integer::sum);
                }
                results[index] = counts; // hand the finished object over
            });
            threads[i].start();
        }
        for (Thread t : threads) t.join(); // after join, main owns the results

        Map<String, Integer> total = new HashMap<>();
        for (Map<String, Integer> counts : results) {
            counts.forEach((w, n) -> total.merge(w, n, Integer::sum));
        }
        int sum = 0;
        for (int n : total.values()) sum += n;
        System.out.println("chunks: " + chunks);
        System.out.println("words counted: " + sum);
        System.out.println("distinct words: " + total.size());
        System.out.println("count of 'a': " + total.get("a"));
    }
}
Output
chunks: 4
words counted: 40000
distinct words: 5
count of 'a': 8000
  • Verdict: idiom. Each thread fills a local HashMap, and join makes the main thread the only owner of the results.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;

class Program
{
    static void Main()
    {
        string[] words = { "a", "b", "c", "d", "e" };
        int chunks = 4;
        var results = new Dictionary<string, int>[chunks];
        var threads = new Thread[chunks];
        for (int i = 0; i < chunks; i++)
        {
            int index = i;
            threads[i] = new Thread(() =>
            {
                var counts = new Dictionary<string, int>(); // local: no lock
                for (int r = 0; r < 2000; r++)
                    foreach (var w in words)
                        counts[w] = counts.GetValueOrDefault(w) + 1;
                results[index] = counts; // hand the finished object over
            });
            threads[i].Start();
        }
        foreach (var t in threads) t.Join(); // after Join, Main owns the results

        var total = new Dictionary<string, int>();
        foreach (var counts in results)
            foreach (var (w, n) in counts)
                total[w] = total.GetValueOrDefault(w) + n;
        Console.WriteLine("chunks: " + chunks);
        Console.WriteLine("words counted: " + total.Values.Sum());
        Console.WriteLine("distinct words: " + total.Count);
        Console.WriteLine("count of 'a': " + total["a"]);
    }
}
Output
chunks: 4
words counted: 40000
distinct words: 5
count of 'a': 8000
  • Verdict: idiom. Each thread fills a local Dictionary, and Join makes the main thread the only owner of the results.
JavaScriptGitHub
const { Worker } = require("node:worker_threads");

// Each worker has its own heap, so its counts object is confined to it.
const workerCode = `
const { parentPort, workerData } = require("node:worker_threads");
const counts = {};
for (let r = 0; r < 2000; r++) {
  for (const w of workerData) counts[w] = (counts[w] || 0) + 1;
}
parentPort.postMessage(counts); // the main thread receives a copy
`;

const words = ["a", "b", "c", "d", "e"];
const chunks = 4;
const runs = [];
for (let i = 0; i < chunks; i++) {
  runs.push(
    new Promise((resolve) => {
      new Worker(workerCode, { eval: true, workerData: words }).on("message", resolve);
    }),
  );
}

Promise.all(runs).then((results) => {
  const total = {};
  for (const counts of results) {
    for (const [w, n] of Object.entries(counts)) total[w] = (total[w] || 0) + n;
  }
  console.log("chunks:", chunks);
  console.log("words counted:", Object.values(total).reduce((a, b) => a + b, 0));
  console.log("distinct words:", Object.keys(total).length);
  console.log("count of 'a':", total["a"]);
});
Output
chunks: 4
words counted: 40000
distinct words: 5
count of 'a': 8000
  • Verdict: idiom. Each worker thread has its own counts object that no other thread can reach, and postMessage gives the main thread a copy.
TypeScriptGitHub
import { Worker } from "node:worker_threads";

// Each worker has its own heap, so its counts object is confined to it.
const workerCode = `
const { parentPort, workerData } = require("node:worker_threads");
const counts = {};
for (let r = 0; r < 2000; r++) {
  for (const w of workerData) counts[w] = (counts[w] || 0) + 1;
}
parentPort.postMessage(counts); // the main thread receives a copy
`;

const words = ["a", "b", "c", "d", "e"];
const chunks = 4;
const runs: Promise<Record<string, number>>[] = [];
for (let i = 0; i < chunks; i++) {
  runs.push(
    new Promise((resolve) => {
      new Worker(workerCode, { eval: true, workerData: words }).on("message", resolve);
    }),
  );
}

Promise.all(runs).then((results) => {
  const total: Record<string, number> = {};
  for (const counts of results) {
    for (const [w, n] of Object.entries(counts)) total[w] = (total[w] || 0) + n;
  }
  console.log("chunks:", chunks);
  console.log("words counted:", Object.values(total).reduce((a, b) => a + b, 0));
  console.log("distinct words:", Object.keys(total).length);
  console.log("count of 'a':", total["a"]);
});
Output
chunks: 4
words counted: 40000
distinct words: 5
count of 'a': 8000
  • Verdict: idiom. Each worker thread has its own counts object that no other thread can reach, and postMessage gives the main thread a copy.
package main

import "fmt"

func main() {
	words := []string{"a", "b", "c", "d", "e"}
	const chunks = 4
	results := make(chan map[string]int)
	for i := 0; i < chunks; i++ {
		go func() {
			counts := map[string]int{} // local: no lock
			for r := 0; r < 2000; r++ {
				for _, w := range words {
					counts[w]++
				}
			}
			results <- counts // send the map and stop using it
		}()
	}

	total := map[string]int{}
	for i := 0; i < chunks; i++ {
		for w, n := range <-results {
			total[w] += n
		}
	}
	sum := 0
	for _, n := range total {
		sum += n
	}
	fmt.Println("chunks:", chunks)
	fmt.Println("words counted:", sum)
	fmt.Println("distinct words:", len(total))
	fmt.Println("count of 'a':", total["a"])
}
Output
chunks: 4
words counted: 40000
distinct words: 5
count of 'a': 8000
  • Verdict: idiom. Each goroutine fills a local map and sends it on a channel, so only one goroutine has the map at a time.
RustGitHub
use std::collections::HashMap;
use std::thread;

fn main() {
    let words = ["a", "b", "c", "d", "e"];
    let chunks = 4;
    let handles: Vec<_> = (0..chunks)
        .map(|_| {
            thread::spawn(move || {
                let mut counts: HashMap<&str, usize> = HashMap::new(); // owned by this thread
                for _ in 0..2000 {
                    for w in words {
                        *counts.entry(w).or_insert(0) += 1;
                    }
                }
                counts // ownership moves to the thread that joins
            })
        })
        .collect();

    let mut total: HashMap<&str, usize> = HashMap::new();
    for h in handles {
        for (w, n) in h.join().unwrap() {
            *total.entry(w).or_insert(0) += n;
        }
    }
    println!("chunks: {}", chunks);
    println!("words counted: {}", total.values().sum::<usize>());
    println!("distinct words: {}", total.len());
    println!("count of 'a': {}", total["a"]);
}
Output
chunks: 4
words counted: 40000
distinct words: 5
count of 'a': 8000
  • Verdict: native. The move closure gives each thread ownership of its HashMap, and join moves the map to the main thread.

Consequences

Benefits:

  • Confinement solves the race condition by not sharing the mutable state.1 The confined code needs no locks.
  • Code that is not thread-safe can still be used, if only its owner thread calls it.2
  • In Go, data races cannot occur, by design, when values pass on channels and only one goroutine has the value at a time.3

Liabilities:

  • In most languages the rule is a convention. Unlike local variables, static variables are not automatically thread confined: if a program has them, the programmer has to argue that only one thread will ever use them, and document it.1 Programs that ignore the Swing rule may function correctly most of the time, but are subject to unpredictable errors that are difficult to reproduce.2
  • An owner thread can become a bottleneck. Tasks on the event dispatch thread must finish quickly. If they do not, unhandled events back up and the user interface becomes unresponsive.2

A reference that escapes breaks the confinement, and nothing reports it:

This code runs but gives a wrong answer on purpose.

import threading

escaped = []  # a global: not confined to any thread
published = threading.Event()
changed = threading.Event()


def worker():
    items = [1, 2, 3]  # meant to be confined to this thread
    escaped.append(items)  # wrong: the reference escapes
    published.set()
    changed.wait()
    print("worker expected sum 6, got:", sum(items))


t = threading.Thread(target=worker)
t.start()
published.wait()
escaped[0].append(100)  # another thread changes the "confined" list
changed.set()
t.join()
Output
worker expected sum 6, got: 106

When not to use it

Do not confine data that many threads must update often at the same time, such as a shared counter of requests. Each update must then go through the owner thread. Effective Go notes that the channel approach can be taken too far: reference counts may be best done by putting a mutex around an integer variable.3

  • Owner thread with a task queue. Other threads put functions on the owner's queue, the same form as invokeLater in Swing.2 The example confines a label to its owner thread:
import queue
import threading

tasks = queue.Queue()
label = {"text": ""}  # confined to the owner thread


def owner():
    while (task := tasks.get()) is not None:
        task()


def invoke_later(fn):  # other threads send work instead of touching label
    tasks.put(fn)


owner_thread = threading.Thread(target=owner)
owner_thread.start()
ran_on_owner = []


def make_update(n):
    def update():
        ran_on_owner.append(threading.current_thread() is owner_thread)
        label["text"] = f"done {n}"
    return update


helpers = [threading.Thread(target=invoke_later, args=(make_update(n),)) for n in (1, 2, 3)]
for h in helpers:
    h.start()
    h.join()
tasks.put(None)
owner_thread.join()
print("label:", label["text"])
print("updates ran on the owner thread:", all(ran_on_owner) and len(ran_on_owner) == 3)
Output
label: done 3
updates ran on the owner thread: True
  • Compiler-checked ownership. In Rust, the Send marker trait indicates that ownership of values of the type can be transferred between threads.4 Rc<T> does not implement Send, so the type system ensures that a program can never accidentally send an Rc<T> value across threads unsafely.4
  • Transferable objects. In JavaScript, a transferable object such as an ArrayBuffer can move from one thread to another. Following a transfer, the original object is no longer usable, and any attempt to read or write it throws an exception.5

Thread-Specific Storage gives each thread its own copy of one logical object. Active Object confines an object to its own thread and turns method calls into requests on a queue.

Known uses

  • Swing confines its components to the event dispatch thread.2
  • Go programs pass values on channels, by the slogan "Do not communicate by sharing memory; instead, share memory by communicating."3
  • Rust types such as Rc<T> are confined to one thread by the compiler.4
  • Web workers transfer an ArrayBuffer, so that its memory is attached to only one thread at a time.5

References

  1. MIT 6.031 Software Construction, Reading 20: Thread Safety, Strategy 1, Confinement; Avoid Global Variables
  2. The Event Dispatch Thread, The Java Tutorials, whole page
  3. Effective Go, Concurrency, Share by communicating
  4. The Rust Programming Language, 16.4 Extensible Concurrency with Send and Sync, Transferring Ownership Between Threads
  5. Transferable objects, MDN Web Docs, introduction

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source