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
- Helps prevent: Data race
- See also: Message passing, Thread-local storage, UI thread
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¶
- In the books: Pro TBB, Michael Voss, Rafael Asenjo, James Reinders — ch. 12, 'Using Work Isolation for Correctness and Performance'
- In the books: Programming Concurrency on the JVM, Venkat Subramaniam — ch. 8, 'Favoring Isolated Mutability'
- In the books: Concurrency in Go, Katherine Cox-Buday — ch. 4, 'Concurrency Patterns in Go' → 'Confinement'
- In the books: Java Concurrency in Practice, Brian Goetz, Tim Peierls, Joshua Bloch, Joseph Bowbeer, David Holmes, Doug Lea — ch. 3, 'Sharing Objects' → 'Thread Confinement'
- In the books: The Go Programming Language Phrasebook, David Chisnall — ch. 10, 'Concurrency Design Patterns' → 'Aliased xor Mutable'