Conceptcore
Thread-local storage
Also called TLS, thread-local variable, thread-specific data, ThreadLocal, thread_local, threading.local, ThreadStatic, pthread_key_create, _Thread_local.
Thread-local storage gives each thread its own copy of a variable. Code reads and writes the variable by one name, and each thread sees only its own value.
- Applies to
- core-languages
Idea
A thread-local variable has a separate value for each thread. All threads use the same name for it, but a read or a write in one thread uses only the value of that thread. The Java documentation says that each thread that uses one "has its own, independently initialized copy of the variable".1
Wikipedia gives the classic reason. The C library reports errors in a global variable, errno. With many threads, a call in one thread could overwrite the error code of a call in another thread before that thread reads it. The solution is to make errno look global but store it "in a per-thread memory pool, the thread-local storage".2
A second use is to avoid locks. Each thread can add to its own thread-local total with no lock, and the threads combine the totals once at the end.2 A third use is to pass context, such as the current user or transaction, down a call chain without a parameter on every method.13
How it works
Keys and slots
The oldest form is an API with keys. A program creates a key once. Each thread can then store one value under the key and read it back:24
- POSIX.
pthread_key_createcreates "a thread-specific data key visible to all threads in the process". Each thread binds its own value to the key withpthread_setspecificand reads it withpthread_getspecific.4 - Windows.
TlsAllocreturns an unused slot index, andTlsSetValueandTlsGetValuewrite and read the value of the current thread in that slot.2
A key can have a destructor. When a thread exits with a value under the key, the system calls the destructor with that value, so the thread can free memory or close connections.42
Language support
Most languages hide the keys behind a variable or an object:
- A storage class. C++ marks a variable
thread_local. The variable has thread storage duration: "There is a distinct object or reference per thread", and the object lasts as long as its thread.5 C11 has the keyword_Thread_local, and C23 makesthread_locala keyword.2 In .NET, a static field with[ThreadStatic]"is unique for each thread".6 - An object. Java
ThreadLocal, .NETThreadLocal<T>, and Pythonthreading.localare objects with a different value in each thread.178 Rust'sthread_local!macro declares aLocalKey, which gives a reference to the value of the current thread inside a closure.910
The compiler and the runtime usually find the value of the current thread through a register. On RISC machines, "the calling convention often reserves a thread pointer register for this use".2
Initialization and cleanup
A new thread does not see the values of other threads. It starts with an initial value, or with no value:
- In Rust, "Initialization is dynamically performed" on the first use in each thread, and the value is dropped when the thread exits.10
- Java
ThreadLocal.withInitialtakes a function that makes the first value in each thread.1 - Python
threading.localhas no attributes in a new thread. In the documentation's example, a new thread sees an empty dictionary, and "changes made in the other thread don’t affect data seen in this thread".8
The examples show this. Each thread counts on its own thread-local counter. The main thread counts to 3, and the threads count to 1 and 2, with no lock and no effect on each other.
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Native | |
| Java | Standard library | |
| C | Native | C11 has the _Thread_local keyword, C23 makes thread_local a keyword, and POSIX has pthread_key_create. No separate example file. Alternative: The same storage class as the C++ example. |
| C# | Standard library | |
| JavaScript | Absent | |
| TypeScript | Absent | TypeScript runs on a JavaScript engine, where threads share no variables. No example file exists. Alternative: AsyncLocalStorage in Node.js, as in the JavaScript example. |
| Go | Absent | |
| Rust | Standard library | |
| Kotlin | Standard library | On the JVM, Kotlin uses the Java ThreadLocal, as in the Java example; no example file because kotlinc is not installed on the machine that recorded the examples. |
| SQL | Does not apply | A query has no threads. |
| Bash | Does not apply | A Bash script runs in one thread for each process. |
| PowerShell | Absent | PowerShell has no thread-local variables in the language; no example file because pwsh is not installed on the machine that recorded the examples. |
| HTML | Does not apply | Markup has no threads. |
| CSS | Does not apply | Style rules have no threads. |
| Regular expressions | Does not apply | A pattern has no threads. |
| Language | Verdict | Mechanism |
|---|---|---|
| Python | stdlib | threading.local |
| JavaScript | absent | no shared variables between threads; AsyncLocalStorage in Node.js |
| TypeScript | absent | as JavaScript |
| Java | stdlib | ThreadLocal, InheritableThreadLocal |
| Kotlin | stdlib | the Java ThreadLocal on the JVM |
| C# | stdlib | [ThreadStatic], ThreadLocal<T> |
| Go | absent | values passed to each goroutine; context.Context |
| Rust | stdlib | the thread_local! macro and LocalKey |
| C | native | _Thread_local, or thread_local in C23; tss_ functions; pthread_key_create |
| C++ | native | the thread_local storage class |
| Bash | n/a | one thread for each process |
| PowerShell | absent | no thread-local variables in the language |
| SQL | n/a | a session has its own settings, but a query has no threads |
| Regex | n/a | a pattern has no threads |
| HTML/CSS | n/a | markup and style rules have no threads |
- Java.
ThreadLocalinstances "are typically private static fields in classes that wish to associate state with a thread".1 A thread keeps its copy "as long as the thread is alive", and after the thread ends, its copies can be garbage-collected.1 - C#. A field with
[ThreadStatic]must also bestatic. Do not give it an initial value in the declaration: that code runs once, "and therefore affects only one thread".6ThreadLocal<T>takes a factory that makes the value for each thread.7 - Python.
threading.local()returns an object whose attributes are "thread specific".8 A subclass can set defaults and methods.8 - Rust. A
LocalKeygives a reference to the value only insidewith, and that reference "cannot outlive the current thread or escape the given closure".10 To change the value, store it in aCellor aRefCell.9 - Go. Goroutines "expose no unique identifier, name, or data structure to the programmer", so there is nothing to attach a goroutine-local value to.11 The FAQ gives the reason: if a package tied state to one goroutine, its users could not use more goroutines for one request.11 Go code passes state as values, and passes request values in a
context.Context. - JavaScript. A worker is "an independent JavaScript execution thread", and workers share memory only through
ArrayBuffertransfers andSharedArrayBuffer.12 So every global variable is already local to its thread. Node.js also hasAsyncLocalStorage, which keeps a value through callbacks and promise chains. Node.js says that it "is similar to thread-local storage in other languages".13
import threading
from concurrent.futures import ThreadPoolExecutor
state = threading.local()
def bump(times):
# Each thread sees its own state.counter. A new thread starts without one.
for _ in range(times):
state.counter = getattr(state, "counter", 0) + 1
return state.counter
results = {}
def worker(name, times):
results[name] = bump(times)
threads = [threading.Thread(target=worker, args=(f"thread {i}", i)) for i in (1, 2)]
for t in threads:
t.start()
for t in threads:
t.join()
results["main"] = bump(3)
for name in ("main", "thread 1", "thread 2"):
print(f"{name}: counter = {results[name]}")
# A pool reuses its threads, so a value that one task leaves behind is seen by the next task.
with ThreadPoolExecutor(max_workers=1) as pool:
pool.submit(setattr, state, "user", "alice").result()
print("a later task on the same thread sees user:", pool.submit(getattr, state, "user", None).result())
pool.submit(delattr, state, "user").result()
print("after a task removes it, the next task sees user:", pool.submit(getattr, state, "user", None).result())
main: counter = 3
thread 1: counter = 1
thread 2: counter = 2
a later task on the same thread sees user: alice
after a task removes it, the next task sees user: None
- Verdict: stdlib.
threading.local()returns an object whose attributes are different in each thread. A new thread sees none of the attributes that other threads set. getattr(state, "counter", 0)gives the default for a thread that has not set the counter yet.- The pool has one worker thread, so all its tasks run on that thread. The value that the first task sets is still there for the next task, until a task deletes it.
- For async code on one thread, use
contextvarsinstead. AContextVarbelongs to a context, not to a thread.
#include <condition_variable>
#include <deque>
#include <functional>
#include <iostream>
#include <mutex>
#include <optional>
#include <string>
#include <thread>
// Each thread gets its own counter, which starts at 0.
thread_local int counter = 0;
thread_local std::optional<std::string> user;
int bump(int times) {
for (int i = 0; i < times; ++i) ++counter;
return counter;
}
int main() {
int one = 0;
int two = 0;
{
std::jthread t1([&] { one = bump(1); });
std::jthread t2([&] { two = bump(2); });
} // the jthreads join here
std::cout << "main: counter = " << bump(3) << '\n';
std::cout << "thread 1: counter = " << one << '\n';
std::cout << "thread 2: counter = " << two << '\n';
// A worker thread that runs one task after another, as a pool thread does.
std::deque<std::function<void()>> tasks{
[] { user = "alice"; },
[] { std::cout << "a later task on the same thread sees user: " << user.value_or("nullopt") << '\n'; },
[] { user.reset(); },
[] { std::cout << "after a task removes it, the next task sees user: " << user.value_or("nullopt") << '\n'; },
};
std::jthread worker([&] {
for (auto& task : tasks) task();
});
}
main: counter = 3
thread 1: counter = 1
thread 2: counter = 2
a later task on the same thread sees user: alice
after a task removes it, the next task sees user: nullopt
- Verdict: native. A variable declared
thread_localhas thread storage duration: each thread has its own object, which lasts as long as the thread. std::jthreadjoins in its destructor, so the closing brace waits for both threads.- The worker thread runs four tasks in order, as a pool thread does. The value that the first task sets stays until a task resets it.
- C has the same feature:
_Thread_localin C11, andthread_localas a keyword in C23.
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
// Each thread gets its own counter, which starts at 0.
static final ThreadLocal<Integer> COUNTER = ThreadLocal.withInitial(() -> 0);
static final ThreadLocal<String> USER = new ThreadLocal<>();
static int bump(int times) {
for (int i = 0; i < times; i++) COUNTER.set(COUNTER.get() + 1);
return COUNTER.get();
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
Map<String, Integer> results = new ConcurrentHashMap<>();
Thread t1 = new Thread(() -> results.put("thread 1", bump(1)));
Thread t2 = new Thread(() -> results.put("thread 2", bump(2)));
t1.start();
t2.start();
t1.join();
t2.join();
results.put("main", bump(3));
for (String name : new String[] {"main", "thread 1", "thread 2"}) {
System.out.println(name + ": counter = " + results.get(name));
}
// A pool reuses its threads, so a value that one task leaves behind is seen by the next task.
try (ExecutorService pool = Executors.newSingleThreadExecutor()) {
pool.submit(() -> USER.set("alice")).get();
System.out.println("a later task on the same thread sees user: " + pool.submit(USER::get).get());
pool.submit(USER::remove).get();
System.out.println("after a task removes it, the next task sees user: " + pool.submit(USER::get).get());
}
}
}
main: counter = 3
thread 1: counter = 1
thread 2: counter = 2
a later task on the same thread sees user: alice
after a task removes it, the next task sees user: null
- Verdict: stdlib.
ThreadLocalgives each thread its own, independently initialized copy.withInitialsets the starting value for each thread. - A single-thread executor runs all its tasks on one thread. The value that the first task sets stays until a task calls
remove. - In a pool, call
removewhen a task ends, usually in afinallyblock, so that the next task does not see the value. InheritableThreadLocalcopies values from a parent thread to its child threads. Scoped values are a newer API for data that flows one way, from a caller to the methods that it calls.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Threading;
static class Program
{
// Each thread gets its own copy of a [ThreadStatic] field, which starts at 0.
[ThreadStatic] static int counter;
static readonly ThreadLocal<string?> User = new();
static int Bump(int times)
{
for (int i = 0; i < times; i++) counter++;
return counter;
}
static void Main()
{
var results = new ConcurrentDictionary<string, int>();
var t1 = new Thread(() => results["thread 1"] = Bump(1));
var t2 = new Thread(() => results["thread 2"] = Bump(2));
t1.Start();
t2.Start();
t1.Join();
t2.Join();
results["main"] = Bump(3);
foreach (var name in new[] { "main", "thread 1", "thread 2" })
Console.WriteLine($"{name}: counter = {results[name]}");
// A worker thread that runs one task after another, as a pool thread does.
var output = new List<string>();
Action[] tasks =
[
() => User.Value = "alice",
() => output.Add($"a later task on the same thread sees user: {User.Value ?? "null"}"),
() => User.Value = null,
() => output.Add($"after a task removes it, the next task sees user: {User.Value ?? "null"}"),
];
var worker = new Thread(() =>
{
foreach (var task in tasks) task();
});
worker.Start();
worker.Join();
output.ForEach(Console.WriteLine);
}
}
main: counter = 3
thread 1: counter = 1
thread 2: counter = 2
a later task on the same thread sees user: alice
after a task removes it, the next task sees user: null
- Verdict: stdlib. A static field with
[ThreadStatic]has a separate value in each thread.ThreadLocal<T>is a class with the same effect and a factory for the starting value. - Do not give a
[ThreadStatic]field an initial value in its declaration. That code runs once, so only one thread gets the value. Here each thread starts at 0, the default. - The worker thread runs four tasks in order, as a pool thread does. The value that the first task sets stays until a task clears it.
- For values that must follow
awaitfrom thread to thread, .NET hasAsyncLocal<T>.
import { AsyncLocalStorage } from "node:async_hooks";
import { Worker } from "node:worker_threads";
// Each thread has its own global object. A worker does not see the globals of the main thread.
function bump(times) {
globalThis.counter ??= 0;
for (let i = 0; i < times; i++) globalThis.counter += 1;
return globalThis.counter;
}
const mainCount = bump(3); // the main thread counts first
const workerCode = `
const { parentPort, workerData } = require("node:worker_threads");
${bump.toString()}
parentPort.postMessage(bump(workerData));
`;
function runWorker(times) {
return new Promise((resolve, reject) => {
const worker = new Worker(workerCode, { eval: true, workerData: times });
worker.once("message", resolve);
worker.once("error", reject);
});
}
const [one, two] = await Promise.all([runWorker(1), runWorker(2)]);
console.log(`main: counter = ${mainCount}`);
console.log(`worker 1: counter = ${one}`);
console.log(`worker 2: counter = ${two}`);
// On one thread, AsyncLocalStorage keeps a value for one chain of calls and callbacks.
const storage = new AsyncLocalStorage();
const show = (text) => console.log(text, storage.getStore()?.user ?? "undefined");
await storage.run({ user: "alice" }, async () => {
await Promise.resolve();
show("the task with the value sees user:");
});
show("a later task on the same thread sees user:");
main: counter = 3
worker 1: counter = 1
worker 2: counter = 2
the task with the value sees user: alice
a later task on the same thread sees user: undefined
- Verdict: absent. JavaScript has no thread-local variables, because threads do not share variables at all. Each worker thread has its own global object, so the workers do not see the counter of the main thread.
- The worker code gets the same
bumpfunction as source text. The workers count from 0, though the main thread counted to 3 first. - On one thread, Node.js has
AsyncLocalStorage, which keeps a value for one chain of calls, callbacks and promises. It is "similar to thread-local storage in other languages". - The value set by
runis still there afterawait, but code outsiderundoes not see it.
package main
import (
"context"
"fmt"
"sync"
)
// Go has no thread-local storage. Each goroutine gets its own state as a value that it owns.
type state struct{ counter int }
func (s *state) bump(times int) int {
for range times {
s.counter++
}
return s.counter
}
type userKey struct{}
// show reads a value that travels with the context, not with the goroutine.
func show(ctx context.Context, text string) {
user, ok := ctx.Value(userKey{}).(string)
if !ok {
user = "none"
}
fmt.Println(text, user)
}
func main() {
results := make([]int, 3)
var wg sync.WaitGroup
for i := 1; i <= 2; i++ {
wg.Add(1)
go func() {
defer wg.Done()
var s state // this goroutine's own state
results[i] = s.bump(i)
}()
}
wg.Wait()
var mainState state
results[0] = mainState.bump(3)
fmt.Println("main: counter =", results[0])
fmt.Println("goroutine 1: counter =", results[1])
fmt.Println("goroutine 2: counter =", results[2])
// A worker goroutine that runs one task after another. Each task gets its own context,
// so a value from one task cannot reach the next.
tasks := make(chan func())
done := make(chan struct{})
go func() {
for task := range tasks {
task()
}
close(done)
}()
tasks <- func() {
show(context.WithValue(context.Background(), userKey{}, "alice"), "the task with the value sees user:")
}
tasks <- func() { show(context.Background(), "a later task on the same goroutine sees user:") }
close(tasks)
<-done
}
main: counter = 3
goroutine 1: counter = 1
goroutine 2: counter = 2
the task with the value sees user: alice
a later task on the same goroutine sees user: none
- Verdict: absent. Go has no thread-local or goroutine-local storage, and goroutines have no ID that a program could use as a key. The Go FAQ explains that this keeps code free to use more goroutines for one job.
- Each goroutine gets its own state as a value that it owns. Here the closure declares
sinside the goroutine. - For values that belong to a request, Go passes a
context.Contextas an argument. A value in a context reaches only the code that gets that context, so the second task does not see it.
use std::cell::{Cell, RefCell};
use std::sync::mpsc;
use std::thread;
thread_local! {
// Each thread gets its own counter, which starts at 0.
static COUNTER: Cell<u32> = const { Cell::new(0) };
static USER: RefCell<Option<String>> = const { RefCell::new(None) };
}
fn bump(times: u32) -> u32 {
for _ in 0..times {
COUNTER.set(COUNTER.get() + 1);
}
COUNTER.get()
}
fn main() {
let (one, two) = thread::scope(|s| {
let one = s.spawn(|| bump(1));
let two = s.spawn(|| bump(2));
(one.join().unwrap(), two.join().unwrap())
});
println!("main: counter = {}", bump(3));
println!("thread 1: counter = {one}");
println!("thread 2: counter = {two}");
// A worker thread that takes tasks from a channel, as a pool thread does.
let (send, receive) = mpsc::channel::<Box<dyn FnOnce() + Send>>();
let worker = thread::spawn(move || {
for task in receive {
task();
}
});
let show = |text: &'static str| -> Box<dyn FnOnce() + Send> {
Box::new(move || {
let user = USER.with_borrow(|u| u.clone().unwrap_or_else(|| "None".to_string()));
println!("{text} {user}");
})
};
send.send(Box::new(|| USER.set(Some("alice".to_string())))).unwrap();
send.send(show("a later task on the same thread sees user:")).unwrap();
send.send(Box::new(|| USER.set(None))).unwrap();
send.send(show("after a task removes it, the next task sees user:")).unwrap();
drop(send);
worker.join().unwrap();
}
main: counter = 3
thread 1: counter = 1
thread 2: counter = 2
a later task on the same thread sees user: alice
after a task removes it, the next task sees user: None
- Verdict: stdlib. The
thread_local!macro declares aLocalKey. Each thread gets its own value, which it creates on first use. CellandRefCellgive mutable access to the value. A thread-local value is not shared, so it does not need aMutex.- The worker thread takes boxed closures from a channel and runs them in order, as a pool thread does. The value that the first task sets stays until a task sets it to
None. - A reference from
withcannot leave the closure or outlive the thread.
Variations and related ideas
- Async-local storage. In async code, one task can move between threads at each
await, and one thread runs many tasks. A thread-local value is then wrong in both directions. .NETAsyncLocal<T>holds data "local to a given asynchronous control flow".14 Python asks code with state to usecontextvars"instead of threading.local() to prevent their state from bleeding to other code unexpectedly".15 - Scoped values. Java scoped values share data one way, from a method to the methods that it calls, for a bounded time. JEP 506 presents them as an answer to three problems of thread-local variables: "Unconstrained mutability", "Unbounded lifetime" and "Expensive inheritance".3
- Inheritance. Java
InheritableThreadLocalcopies values from a parent thread to the child threads that it creates. Each child must allocate storage for every inherited variable, which costs memory with many threads.3 - Fibers. A fiber that reads thread-local storage reads the storage "of the thread that is running it". Windows has fiber-local storage for values that belong to one fiber.16
- Virtual threads. JEP 506 says that the problems of thread-local variables "have become more pressing with the availability of virtual threads", because a program can have millions of them.3
Pitfalls
- Leaks in thread pools. A pool reuses its threads, so a value that one task sets stays for the next task on that thread. JEP 506 warns that "the value of a thread-local variable set in one task could, if not properly cleared, accidentally leak into an unrelated task".3 The examples show this with a pool of one thread. Remove the value at the end of each task, for example in a
finallyblock. - Memory that is never freed. A value stays "for the lifetime of the thread, or until code in the thread calls the remove method".3 The threads of a pool can live as long as the program, so their values can too.3
- Values that cross threads. A value read from a thread-local variable belongs to the thread that read it. Python warns that you "generally don’t want to save these values across threads".8
- Hidden inputs. A method that reads a thread-local variable has an input that is not in its parameters. Any code that can read the variable can also change it, which can make the data flow hard to follow.3
- Async code. After an
await, the code can continue on another thread, with other thread-local values. Use async-local storage for values that must follow the task.1415 - Destructors. Rust does not promise that destructors run for every thread-local value on every platform.10 Do not use a thread-local destructor for work that must happen.
Cost
- Access. A thread-local access must find the storage of the current thread first. With compiler support, this uses a register that points to the thread's data.2 A key-based API makes a function call for each read and write.4
- Memory. Each thread that uses a variable has its own copy, so the memory grows with the number of threads.3 Rust's
constinitializer can "avoid lazy initialization", which makes access cheaper.9 - No locks. A value that only one thread uses needs no lock. This is often the reason to use thread-local storage: per-thread totals replace a shared total with a lock.2
History
POSIX thread-specific data came with the POSIX threads extension. The pthread_key_create page says that it was "Included for alignment with the POSIX Threads Extension".4 Java added ThreadLocal in version 1.2, released in December 1998.317 C++11 added the thread_local keyword, and C11 added _Thread_local.2 Later, async code led to async-local storage, such as contextvars in Python 3.7, AsyncLocal<T> in .NET, and AsyncLocalStorage in Node.js.151413 Java scoped values followed, for the very large numbers of threads that virtual threads allow.3
References
- Java SE 21 API, java.lang.ThreadLocal, class description
- Wikipedia, Thread-local storage, introduction; Usage; Windows implementation; Pthreads implementation; C and C++
- JEP 506: Scoped Values, Motivation; Problems with thread-local variables
- POSIX.1-2024, pthread_key_create, DESCRIPTION; CHANGE HISTORY
- cppreference, Storage duration, Thread storage duration
- Microsoft Learn, ThreadStaticAttribute class, Remarks
- Microsoft Learn, ThreadLocal<T> class, class description; Examples
- Python documentation, threading, Thread-local data
- Rust standard library, macro std::thread_local, Syntax
- Rust standard library, struct std::thread::LocalKey, Initialization and Destruction; Platform-specific behavior
- Go FAQ, Why is there no goroutine ID?
- Node.js documentation, Worker threads, introduction; Class Worker
- Node.js documentation, Asynchronous context tracking, Introduction
- Microsoft Learn, AsyncLocal<T> class, class description
- Python documentation, contextvars, introduction
- Microsoft Learn, Win32 apps, Fibers, Fiber Local Storage
- Wikipedia, Java version history, Release table
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Visual | V0 none |
|
| Writing | W4 complete |
|
Tag 18V7W5 Edit this page History Report an error Markdown