Programming Search⌘K

Patterncore

Thread-Specific Storage

Also called thread-specific storage, thread-local storage, tls, thread-local variable.

Thread-Specific Storage gives each thread its own copy of an object behind one global access point. The code reads and writes the object with no lock, because no other thread can reach that copy.

Family
concurrency
Intent
Allow multiple threads to use one logically global access point to retrieve thread-specific data without incurring locking overhead for each access.
Also called
Thread-Local Storage

Intent

The Thread-Specific Storage pattern allows multiple threads to use one logically global access point to retrieve thread-specific data without incurring locking overhead for each access.1 Wikipedia calls the mechanism thread-local storage: memory that is static or global but local to a thread, so data appears to be global in a system with separate threads.2

Problem

The paper's example is errno. When a system call fails, the OS sets errno and returns a failure status, and the application then checks errno to find the type of error.1 With one global errno per process, a value set by a method in one thread can be interpreted erroneously by other threads.1 Thread T1's recv sets errno to EWOULDBLOCK, T1 is preempted, and T2's recv sets errno to EINTR. Then T1 falsely assumes its recv call was interrupted.1

A mutex around errno does not solve the race, because the call sets the value and the application tests it in two steps.1 A locking protocol in which the application releases the lock after the test is also undesirable: applications can forget to release the lock, and the extra locking overhead degrades performance even when multiple threads are not used.1

Solution

Use one global access point that is logically shared by all threads but physically unique for each thread.1 The participants are:1

  • The Application Thread uses the access point, such as the errno macro.1
  • The TS Object Proxy defines the interface of a TS Object and gives each thread access to its own object through get and set methods. It hides keys and TS Object Collections from the application threads.1
  • The TS Object is a particular thread's instance of a thread-specific object, such as a thread's errno of type int.1
  • The TS Object Collection contains the thread-specific objects of one thread and maps keys to them. Every thread has a unique collection.1
thread T1                         thread T2
errno = EWOULDBLOCK               errno = EINTR
  proxy -> T1's collection          proxy -> T2's collection
        -> key -> T1's errno              -> key -> T2's errno
if errno == EWOULDBLOCK: true     if errno == EINTR: true

Once the proxy finds the object, the thread works on it with ordinary method calls. No locking is necessary, because only the calling thread accesses the object.1 On Solaris, errno is a macro that calls a function, which returns a pointer to the thread-specific value.1

Example

The example files keep a last-error value in thread-specific storage. Four threads each make 1000 calls to a function that stores an error code for its thread and then reads the code back, with a yield to the scheduler between the two steps. The program counts the reads that see another thread's code. The program prints:

threads: 4
calls per thread: 1000
reads that saw another thread's error: 0
error code seen by each thread: [1, 2, 3, 4]
PythonGitHub
import threading
import time

last_error = threading.local()  # one access point, one value per thread


def fake_call(code):
    last_error.code = code  # the call sets its thread's error
    time.sleep(0)  # let another thread run between the set and the test
    return -1


wrong_reads = 0
seen = [None] * 4
count_lock = threading.Lock()


def worker(index):
    global wrong_reads
    code = index + 1
    for _ in range(1000):
        if fake_call(code) == -1 and last_error.code != code:
            with count_lock:
                wrong_reads += 1
    seen[index] = last_error.code


threads = [threading.Thread(target=worker, args=(i,)) for i in range(4)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("threads:", len(threads))
print("calls per thread:", 1000)
print("reads that saw another thread's error:", wrong_reads)
print("error code seen by each thread:", seen)
Output
threads: 4
calls per thread: 1000
reads that saw another thread's error: 0
error code seen by each thread: [1, 2, 3, 4]
  • Verdict: stdlib. threading.local is the access point, and each thread sees its own code attribute.
#include <atomic>
#include <iostream>
#include <thread>
#include <vector>

thread_local int last_error = 0; // one name, one value per thread

int fake_call(int code) {
    last_error = code; // the call sets its thread's error
    std::this_thread::yield(); // let another thread run between the set and the test
    return -1;
}

int main() {
    std::atomic<int> wrong_reads{0};
    int seen[4] = {0, 0, 0, 0};
    std::vector<std::thread> threads;
    for (int index = 0; index < 4; ++index) {
        threads.emplace_back([&, index] {
            int code = index + 1;
            for (int n = 0; n < 1000; ++n) {
                if (fake_call(code) == -1 && last_error != code) ++wrong_reads;
            }
            seen[index] = last_error;
        });
    }
    for (auto& t : threads) t.join();
    std::cout << "threads: " << threads.size() << "\n";
    std::cout << "calls per thread: " << 1000 << "\n";
    std::cout << "reads that saw another thread's error: " << wrong_reads << "\n";
    std::cout << "error code seen by each thread: [" << seen[0] << ", " << seen[1] << ", " << seen[2]
              << ", " << seen[3] << "]\n";
}
Output
threads: 4
calls per thread: 1000
reads that saw another thread's error: 0
error code seen by each thread: [1, 2, 3, 4]
  • Verdict: native. The thread_local keyword gives each thread its own last_error.
JavaGitHub
import java.util.concurrent.atomic.AtomicInteger;

public class Main {
    // One access point, one value per thread.
    static final ThreadLocal<Integer> lastError = ThreadLocal.withInitial(() -> 0);

    static int fakeCall(int code) {
        lastError.set(code); // the call sets its thread's error
        Thread.yield(); // let another thread run between the set and the test
        return -1;
    }

    public static void main(String[] args) throws InterruptedException {
        AtomicInteger wrongReads = new AtomicInteger();
        int[] seen = new int[4];
        Thread[] threads = new Thread[4];
        for (int i = 0; i < 4; i++) {
            final int index = i;
            threads[i] = new Thread(() -> {
                int code = index + 1;
                for (int n = 0; n < 1000; n++) {
                    if (fakeCall(code) == -1 && lastError.get() != code) wrongReads.incrementAndGet();
                }
                seen[index] = lastError.get();
            });
            threads[i].start();
        }
        for (Thread t : threads) t.join();
        System.out.println("threads: " + threads.length);
        System.out.println("calls per thread: " + 1000);
        System.out.println("reads that saw another thread's error: " + wrongReads.get());
        System.out.println("error code seen by each thread: [" + seen[0] + ", " + seen[1] + ", " + seen[2] + ", " + seen[3] + "]");
    }
}
Output
threads: 4
calls per thread: 1000
reads that saw another thread's error: 0
error code seen by each thread: [1, 2, 3, 4]
  • Verdict: stdlib. ThreadLocal is the TS Object Proxy: get and set reach the value of the calling thread.
using System;
using System.Threading;

class Program
{
    [ThreadStatic] private static int lastError; // one field, one value per thread

    static int FakeCall(int code)
    {
        lastError = code; // the call sets its thread's error
        Thread.Yield(); // let another thread run between the set and the test
        return -1;
    }

    static void Main()
    {
        int wrongReads = 0;
        int[] seen = new int[4];
        var threads = new Thread[4];
        for (int i = 0; i < 4; i++)
        {
            int index = i;
            threads[i] = new Thread(() =>
            {
                int code = index + 1;
                for (int n = 0; n < 1000; n++)
                {
                    if (FakeCall(code) == -1 && lastError != code) Interlocked.Increment(ref wrongReads);
                }
                seen[index] = lastError;
            });
            threads[i].Start();
        }
        foreach (var t in threads) t.Join();
        Console.WriteLine("threads: " + threads.Length);
        Console.WriteLine("calls per thread: " + 1000);
        Console.WriteLine("reads that saw another thread's error: " + wrongReads);
        Console.WriteLine("error code seen by each thread: [" + string.Join(", ", seen) + "]");
    }
}
Output
threads: 4
calls per thread: 1000
reads that saw another thread's error: 0
error code seen by each thread: [1, 2, 3, 4]
  • Verdict: native. The [ThreadStatic] attribute gives each thread its own copy of the static field.
JavaScriptGitHub
const { Worker } = require("node:worker_threads");

// Each worker runs this code in its own global scope, so each has its own lastError.
const workerCode = `
const { parentPort, workerData } = require("node:worker_threads");
let lastError = 0;
function fakeCall(code) {
  lastError = code; // the call sets this thread's error
  return -1;
}
const code = workerData + 1;
let wrongReads = 0;
for (let i = 0; i < 1000; i++) {
  if (fakeCall(code) === -1 && lastError !== code) wrongReads += 1;
}
parentPort.postMessage({ wrongReads, seen: lastError });
`;

const runs = [0, 1, 2, 3].map(
  (index) =>
    new Promise((resolve) => {
      new Worker(workerCode, { eval: true, workerData: index }).on("message", resolve);
    }),
);
Promise.all(runs).then((results) => {
  console.log("threads:", results.length);
  console.log("calls per thread:", 1000);
  console.log("reads that saw another thread's error:", results.reduce((n, r) => n + r.wrongReads, 0));
  console.log("error code seen by each thread: [" + results.map((r) => r.seen).join(", ") + "]");
});
Output
threads: 4
calls per thread: 1000
reads that saw another thread's error: 0
error code seen by each thread: [1, 2, 3, 4]
  • Verdict: idiom. Each worker thread runs the worker code in its own global scope, so the top-level lastError of one worker is not visible to the others.
TypeScriptGitHub
import { Worker } from "node:worker_threads";

// Each worker runs this code in its own global scope, so each has its own lastError.
const workerCode = `
const { parentPort, workerData } = require("node:worker_threads");
let lastError = 0;
function fakeCall(code) {
  lastError = code; // the call sets this thread's error
  return -1;
}
const code = workerData + 1;
let wrongReads = 0;
for (let i = 0; i < 1000; i++) {
  if (fakeCall(code) === -1 && lastError !== code) wrongReads += 1;
}
parentPort.postMessage({ wrongReads, seen: lastError });
`;

type Result = { wrongReads: number; seen: number };

const runs = [0, 1, 2, 3].map(
  (index) =>
    new Promise<Result>((resolve) => {
      new Worker(workerCode, { eval: true, workerData: index }).on("message", resolve);
    }),
);
Promise.all(runs).then((results: Result[]) => {
  console.log("threads:", results.length);
  console.log("calls per thread:", 1000);
  console.log("reads that saw another thread's error:", results.reduce((n, r) => n + r.wrongReads, 0));
  console.log("error code seen by each thread: [" + results.map((r) => r.seen).join(", ") + "]");
});
Output
threads: 4
calls per thread: 1000
reads that saw another thread's error: 0
error code seen by each thread: [1, 2, 3, 4]
  • Verdict: idiom. Each worker thread runs the worker code in its own global scope, so the top-level lastError of one worker is not visible to the others.
package main

import (
	"fmt"
	"runtime"
	"strings"
	"sync"
	"sync/atomic"
)

// callState holds the per-goroutine data that errno holds per thread in C.
type callState struct {
	lastError int
}

func fakeCall(s *callState, code int) int {
	s.lastError = code // the call sets this goroutine's error
	runtime.Gosched()  // let another goroutine run between the set and the test
	return -1
}

func main() {
	var wrongReads atomic.Int64
	seen := make([]int, 4)
	var wg sync.WaitGroup
	for index := 0; index < 4; index++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			state := &callState{} // owned by this goroutine only
			code := index + 1
			for n := 0; n < 1000; n++ {
				if fakeCall(state, code) == -1 && state.lastError != code {
					wrongReads.Add(1)
				}
			}
			seen[index] = state.lastError
		}()
	}
	wg.Wait()
	fmt.Println("threads:", len(seen))
	fmt.Println("calls per thread:", 1000)
	fmt.Println("reads that saw another thread's error:", wrongReads.Load())
	codes := make([]string, len(seen))
	for i, c := range seen {
		codes[i] = fmt.Sprint(c)
	}
	fmt.Println("error code seen by each thread: [" + strings.Join(codes, ", ") + "]")
}
Output
threads: 4
calls per thread: 1000
reads that saw another thread's error: 0
error code seen by each thread: [1, 2, 3, 4]
  • Verdict: idiom. Each goroutine creates its own callState and passes it as a parameter, the explicit form that the pattern paper gives as the alternative.
RustGitHub
use std::cell::Cell;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::Arc;
use std::thread;

thread_local! {
    static LAST_ERROR: Cell<i32> = Cell::new(0); // one name, one value per thread
}

fn fake_call(code: i32) -> i32 {
    LAST_ERROR.with(|e| e.set(code)); // the call sets its thread's error
    thread::yield_now(); // let another thread run between the set and the test
    -1
}

fn main() {
    let wrong_reads = Arc::new(AtomicU32::new(0));
    let threads: Vec<_> = (0..4)
        .map(|index| {
            let wrong_reads = Arc::clone(&wrong_reads);
            thread::spawn(move || {
                let code = index + 1;
                for _ in 0..1000 {
                    if fake_call(code) == -1 && LAST_ERROR.with(|e| e.get()) != code {
                        wrong_reads.fetch_add(1, Ordering::Relaxed);
                    }
                }
                LAST_ERROR.with(|e| e.get())
            })
        })
        .collect();
    let seen: Vec<i32> = threads.into_iter().map(|t| t.join().unwrap()).collect();
    println!("threads: {}", seen.len());
    println!("calls per thread: {}", 1000);
    println!("reads that saw another thread's error: {}", wrong_reads.load(Ordering::Relaxed));
    println!("error code seen by each thread: {:?}", seen);
}
Output
threads: 4
calls per thread: 1000
reads that saw another thread's error: 0
error code seen by each thread: [1, 2, 3, 4]
  • Verdict: stdlib. The thread_local! macro declares LAST_ERROR, and with reaches the value of the calling thread.

Consequences

Benefits:1

  • Efficiency. The pattern can be implemented so that no locking is needed for thread-specific data. Each thread can set and test the completion status of methods within that thread without complex synchronization protocols.1
  • Ease of use. System developers can make thread-specific storage completely transparent at the source-code level via data abstraction or macros.1

Liabilities:1

  • It encourages the use of (thread-safe) global variables. Many applications do not need a common access point to thread-specific data. Then the data should be stored so that only the thread owning the data can access it, for example by passing a Logger as a parameter to all functions of an Active Object.1
  • It hides the structure of the system. It hides the relationships between objects in an application, potentially making the application harder to understand.1

The block below shows the race from the paper with one global value. Events force the order of the threads, so the race happens on each run:

This code runs but gives a wrong answer on purpose.

import threading

errno = 0  # one global errno per process
EWOULDBLOCK, EINTR = 35, 4
t1_set = threading.Event()
t2_set = threading.Event()
seen = {}


def t1():
    global errno
    errno = EWOULDBLOCK  # T1's recv sets errno
    t1_set.set()
    t2_set.wait()  # T1 is preempted here
    seen["T1"] = "interrupted" if errno == EINTR else "would block"


def t2():
    global errno
    t1_set.wait()
    errno = EINTR  # T2's recv sets errno
    t2_set.set()


threads = [threading.Thread(target=t1), threading.Thread(target=t2)]
for t in threads:
    t.start()
for t in threads:
    t.join()
print("T1's recv would block, T1 reads:", seen["T1"])
Output
T1's recv would block, T1 reads: interrupted

When not to use it

  • Multiple threads collaborate on a single task that requires concurrent access to shared data, such as an in-memory database. If thread-specific storage held the database, the threads could not share the data.1
  • It is more intuitive and efficient to maintain both a physical and logical separation of data, for example by passing the data explicitly as parameters to all methods.1
  • Tasks of a thread pool must not see each other's data. A pool thread runs many tasks, so a value that one task leaves in thread-specific storage is still there for the next task, as the block below shows.
  • Per-thread Singleton. Objects in thread-specific storage are often used as per-thread Singletons; errno is one. A thread can also have multiple instances of a type in thread-specific storage.1
  • Proxy. The TSS template class of the paper serves as a Proxy that shields applications from the implementation of thread-specific storage in OS thread libraries.1
  • Double-Checked Locking Optimization. Applications that use the pattern commonly use it to avoid constraining the order of initialization for thread-specific storage keys.1
  • Language features. C11 has the _Thread_local keyword, and C++11 introduces thread_local. Java has the ThreadLocal class, C# has the ThreadStatic attribute and the ThreadLocal<T> class, Python has threading.local, and Rust has the thread_local! macro.2 POSA2 lists the pattern among its 17 patterns.3

In Python, a threading.local object holds data whose values are thread specific, and changes made in another thread do not affect the data seen in this thread.4 With a thread pool, one thread runs each task in turn:

import threading
from concurrent.futures import ThreadPoolExecutor

context = threading.local()


def handle(user):
    previous = getattr(context, "user", None)
    context.user = user
    return previous


with ThreadPoolExecutor(max_workers=1) as pool:
    print("task 1 saw:", pool.submit(handle, "alice").result())
    print("task 2 saw:", pool.submit(handle, "bob").result())
print("main thread sees:", getattr(context, "user", None))
Output
task 1 saw: None
task 2 saw: alice
main thread sees: None

Known uses

  • errno. The errno mechanism on platforms that support the POSIX and Solaris threading APIs is a widely used example. The Win32 C runtime library supports a thread-specific errno, and the Win32 GetLastError and SetLastError functions also implement the pattern.1
  • Win32 windows. Windows are owned by threads, and each thread that owns a window has a private message queue in thread-specific storage.1
  • OpenGL. On Win32, the OpenGL library keeps a unique set of state variables in thread-specific storage for each thread that uses the library.1
  • ACE. The ACE network programming toolkit uses thread-specific storage for its error handling scheme and implements type-safe thread-specific storage template wrappers.1

References

  1. Douglas C. Schmidt, Timothy H. Harrison, and Nat Pryce, Thread-Specific Storage for C/C++: An Object Behavioral Pattern for Accessing per-Thread State Efficiently, Abstract; 1 Intent; 2 Motivation; 3 Applicability; 4 Structure and Participants; 6 Consequences; 10 Known Uses; 11 Related Patterns
  2. Thread-local storage, Wikipedia, lead; C and C++; Java; .NET languages; Python; Rust
  3. Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects (POSA2), overview page, Overview, the 17 patterns
  4. threading, Thread-based parallelism, Python documentation, Thread-local data

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/P2W06C/text.yaml