Programming Search⌘K

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_create creates "a thread-specific data key visible to all threads in the process". Each thread binds its own value to the key with pthread_setspecific and reads it with pthread_getspecific.4
  • Windows. TlsAlloc returns an unused slot index, and TlsSetValue and TlsGetValue write 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 makes thread_local a keyword.2 In .NET, a static field with [ThreadStatic] "is unique for each thread".6
  • An object. Java ThreadLocal, .NET ThreadLocal<T>, and Python threading.local are objects with a different value in each thread.178 Rust's thread_local! macro declares a LocalKey, 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.withInitial takes a function that makes the first value in each thread.1
  • Python threading.local has 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

LanguageVerdictNote
PythonStandard library
C++Native
JavaStandard library
CNativeC11 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
JavaScriptAbsent
TypeScriptAbsentTypeScript runs on a JavaScript engine, where threads share no variables. No example file exists. Alternative: AsyncLocalStorage in Node.js, as in the JavaScript example.
GoAbsent
RustStandard library
KotlinStandard libraryOn 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.
SQLDoes not applyA query has no threads.
BashDoes not applyA Bash script runs in one thread for each process.
PowerShellAbsentPowerShell has no thread-local variables in the language; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no threads.
CSSDoes not applyStyle rules have no threads.
Regular expressionsDoes not applyA 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. ThreadLocal instances "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 be static. Do not give it an initial value in the declaration: that code runs once, "and therefore affects only one thread".6 ThreadLocal<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 LocalKey gives a reference to the value only inside with, and that reference "cannot outlive the current thread or escape the given closure".10 To change the value, store it in a Cell or a RefCell.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 ArrayBuffer transfers and SharedArrayBuffer.12 So every global variable is already local to its thread. Node.js also has AsyncLocalStorage, which keeps a value through callbacks and promise chains. Node.js says that it "is similar to thread-local storage in other languages".13
PythonGitHub
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())
Output
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 contextvars instead. A ContextVar belongs 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();
    });
}
Output
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_local has thread storage duration: each thread has its own object, which lasts as long as the thread.
  • std::jthread joins 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_local in C11, and thread_local as a keyword in C23.
JavaGitHub
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());
        }
    }
}
Output
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. ThreadLocal gives each thread its own, independently initialized copy. withInitial sets 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 remove when a task ends, usually in a finally block, so that the next task does not see the value.
  • InheritableThreadLocal copies 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);
    }
}
Output
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 await from thread to thread, .NET has AsyncLocal<T>.
JavaScriptGitHub
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:");
Output
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 bump function 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 run is still there after await, but code outside run does 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
}
Output
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 s inside the goroutine.
  • For values that belong to a request, Go passes a context.Context as an argument. A value in a context reaches only the code that gets that context, so the second task does not see it.
RustGitHub
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();
}
Output
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 a LocalKey. Each thread gets its own value, which it creates on first use.
  • Cell and RefCell give mutable access to the value. A thread-local value is not shared, so it does not need a Mutex.
  • 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 with cannot leave the closure or outlive the thread.
  • 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. .NET AsyncLocal<T> holds data "local to a given asynchronous control flow".14 Python asks code with state to use contextvars "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 InheritableThreadLocal copies 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 finally block.
  • 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 const initializer 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

  1. Java SE 21 API, java.lang.ThreadLocal, class description
  2. Wikipedia, Thread-local storage, introduction; Usage; Windows implementation; Pthreads implementation; C and C++
  3. JEP 506: Scoped Values, Motivation; Problems with thread-local variables
  4. POSIX.1-2024, pthread_key_create, DESCRIPTION; CHANGE HISTORY
  5. cppreference, Storage duration, Thread storage duration
  6. Microsoft Learn, ThreadStaticAttribute class, Remarks
  7. Microsoft Learn, ThreadLocal<T> class, class description; Examples
  8. Python documentation, threading, Thread-local data
  9. Rust standard library, macro std::thread_local, Syntax
  10. Rust standard library, struct std::thread::LocalKey, Initialization and Destruction; Platform-specific behavior
  11. Go FAQ, Why is there no goroutine ID?
  12. Node.js documentation, Worker threads, introduction; Class Worker
  13. Node.js documentation, Asynchronous context tracking, Introduction
  14. Microsoft Learn, AsyncLocal<T> class, class description
  15. Python documentation, contextvars, introduction
  16. Microsoft Learn, Win32 apps, Fibers, Fiber Local Storage
  17. 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.

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)
WritingW4 complete
  • a review of the text: no review record reviews/18V7W5/text.yaml