Skip to content

Thread confinement

Category: Safety in languages · Status: stub

One line: Keeping a piece of data reachable from one thread only — a GUI's main thread, a goroutine that owns its state — so that it needs no synchronization.

Also called: ownership by one thread, confinement, thread-local storage.

How it connects

flowchart LR
  n_data_race["Data race"]
  n_thread_confinement["Thread confinement"]
  n_thread_confinement -->|prevents| n_data_race
  classDef center stroke-width:3px
  class n_thread_confinement center
  classDef outside stroke-dasharray: 4 3
  class n_data_race outside

In each language

Rust Enforced for some types: Rc ↗ is not Send, so it cannot leave its thread; thread_local! ↗ declares per-thread statics
Go By convention: Effective Go ↗ passes values on channels so that only one goroutine has access at any given time
C _Thread_local ↗ (C11), spelled thread_local since C23
Java ThreadLocal ↗: each thread has its own, independently initialized copy
Python threading.local ↗ holds data whose values are thread specific
C# ThreadLocal<T> ↗ provides thread-local storage of data
JavaScript Web workers ↗ receive copies of message data, not the sender's objects

Where to read more