Skip to content

Thread-local storage

Category: Units of execution · Status: stub · Lessons: chapter 02, Shared state

One line: A variable with a separate copy per thread, so each thread sees only its own value and no lock is needed.

Also called: TLS, thread-specific data, thread-local variable.

How it connects

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

In each language

Rust thread_local! declares a LocalKey, read through with
Go None: goroutines are anonymous, with no ID ↗ to attach state to, and request-scoped values travel in a context.Context
C C11 _Thread_local (thread_local since C23), or POSIX pthread_key_create
C++ thread_local (C++11)
Java ThreadLocal, and ScopedValue (JDK 25) for immutable values bound for a scope
Python threading.local; concurrent code should use contextvars instead, so that state does not bleed into other code
C# ThreadLocal<T>, and AsyncLocal<T> for a value that follows an asynchronous flow
Swift TaskLocal values belong to a task and are inherited by its child tasks
Erlang and Elixir Each process has its own process dictionary ↗

Where to read more

  • In the books: Async Rust, Maxwell Flitton, Caroline Morton — ch. 7, 'Customizing Tokio' → 'Getting Unsafe with Thread Data'
  • In the books: Pthreads Programming, Bradford Nichols, Dick Buttlar, Jacqueline Proulx Farrell — ch. 4, 'Managing Pthreads' → 'Keys: Using Thread-Specific Data'
  • In the books: Concurrency with Modern C++, Rainer Grimm — ch. 3, 'Multithreading' → 'Thread-Local Data'
  • In the books: The Art of Concurrency, Clay Breshears — ch. 4, 'Eight Simple Rules for Designing Multithreaded Applications' → 'Rule 7: Use Thread-Local Storage Whenever Possible or Associate Locks to Specific Data'
  • In the books: Programming with POSIX Threads, David R. Butenhof — ch. 5, 'Advanced Threaded Programming' → 'Thread-specific data'
  • In the books: Multi-Threaded Programming in C++, Mark Walmsley — ch. 7, 'Keys' → 'Thread-Specific Storage'
  • Reference: Wikipedia: Thread-local storage ↗