Taskcore
Use thread-local storage
Also called per-thread counter, ThreadLocal example, threading.local example, thread_local example, ThreadStatic example, _Thread_local example, thread-specific data example.
Start one thread for each count. Each thread adds 1 to its own thread-local counter as many times as its count says, with no lock, and returns the final value of its counter.
- Evidence
- Code in 9 languages
Task
Write a function count_per_thread(counts) that starts one thread for each count. Thread i calls a function bump() counts[i] times. bump has no parameters: it adds 1 to the counter of the thread that calls it and returns the new value. The counter is a thread-local variable, so each thread has its own counter, which starts at 0. When thread i has finished, it reads its counter, and the function returns these values in the order of the counts. For example, count_per_thread([1, 2, 3]) is [1, 2, 3].
There are 0 to 16 counts, and each count is 0 to 100,000. The result is always equal to counts. That is the point of the task: the threads use one name for the counter, but no thread sees the counts of another thread, and the counter needs no lock. A second function current() returns the counter of the calling thread. The tests call bump() 3 times on one thread, then call count_per_thread, and check that current() on that thread is still 3. Thread-local storage explains the idea.
Solutions
| Language | Thread-local counter | Threads | Results |
|---|---|---|---|
| Python | an attribute of a threading.local() object |
threading.Thread, then join |
a list slot for each thread |
| JavaScript | a module variable; each worker loads the module again | new Worker(new URL(import.meta.url)) |
a message from each worker |
| TypeScript | as JavaScript | as JavaScript | as JavaScript |
| Java | ThreadLocal.withInitial(() -> 0) |
Thread.ofPlatform().start, then join |
an array slot for each thread |
| C# | a static int field with [ThreadStatic] |
new Thread, Start, then Join |
an array slot for each thread |
| Go | none; each goroutine owns a Counter value |
go statements and a sync.WaitGroup |
a slice element for each goroutine |
| Rust | thread_local! with a Cell<u32> |
thread::scope and spawn |
the return value of join |
| C | static _Thread_local int32_t |
pthread_create, then pthread_join |
a struct for each thread |
| C++ | a thread_local std::int32_t |
std::jthread |
a vector element for each thread |
- Python has
threading.local. "Thread-local data is data whose values are thread specific": the program makes onelocalobject and uses its attributes.1 A new thread sees no attribute, sobumpreads the counter withgetattrand the default 0. - Java uses one
ThreadLocal. Each thread that uses it "has its own, independently initialized copy of the variable".2withInitialtakes aSupplierthat gives the first value in each thread.2 The field isprivate static final, as the documentation suggests:ThreadLocalinstances "are typically private static fields in classes that wish to associate state with a thread".2 - C# marks a static field with
[ThreadStatic]. Such a field "is not shared between threads", and each thread has "a separate instance of the field".3 The field has no initializer, so it starts at its default value, 0, in every thread.3 - Rust declares the counter with
thread_local!, which declares "a new thread local storage key of type std::thread::LocalKey".4 The value is aCell, sobumpcan change it through the shared reference thatwithgives. The initializer is aconstblock, which "can avoid lazy initialization".4 Without it, "Initialization is dynamically performed" on the first use in each thread.5 The threads run inthread::scope, and each one returns its counter as the result of its closure. - C++ declares the counter
thread_local. For such a variable, the storage "lasts for the duration of the thread in which they are created", and each thread has its own object.6 Thestd::jthreadobjects are in a block, and their destructors join the threads at the end of the block. - C declares the counter
_Thread_local. C11 added this keyword, and C23 makesthread_locala keyword too.7 The threads come frompthread_create, and each one writes its result to its own struct. - Go has no thread-local storage. Goroutines "expose no unique identifier, name, or data structure to the programmer", so there is nothing to attach a goroutine-local value to.8 The solution does what Go code does instead: each goroutine makes its own
Counterand calls its methods. Code that needs the counter gets it as a value, so the call chain shows where the state goes. - JavaScript and TypeScript have no thread-local variables, because threads share no variables. A
Workeris "an independent JavaScript execution thread".9 The solution starts each worker on the file of its own module, as the Node.js documentation does, where the call "re-loads the current file inside a Worker instance".9 So each worker has its own copy of the module and of itscountervariable.isMainThreadtells the module whether it runs in a worker.9
Alternatives
ThreadLocal<T>in .NET. It "Provides thread-local storage of data", and its constructor can take a factory for the first value of each thread.10 WithtrackAllValues, itsValuesproperty "Gets a list containing the values stored by all threads that have accessed this instance".10 Then the threads do not have to report their counters: the caller reads all of them.- Keys in POSIX.
pthread_key_createcreates "a thread-specific data key visible to all threads in the process".11 Each thread stores a pointer under the key withpthread_setspecificand reads it withpthread_getspecific. A key can have a destructor, which frees the value of a thread when that thread exits.11 - Cell methods in Rust. A
LocalKey<Cell<T>>hasgetandsetmethods.get"Returns a copy of the contained value", soCOUNTER.set(COUNTER.get() + 1)works withoutwith.5 - Async-local storage. Code that uses
asyncandawaitshould keep per-task values inAsyncLocalStoragein Node.js, which "is similar to thread-local storage in other languages",12 or incontextvarsin Python, which code with state should use "instead of threading.local()".13
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
empty: no counts start no threads and give an empty list.zero: a thread that never callsbumpreturns 0. Its counter starts at 0. It does not start at the value of the caller's counter.one-thread: one thread gives one counter.equal-counts: 4 threads count to 100 each. With one shared counter, the threads would see each other's counts, and the results could be as large as 400.many-threads: 16 threads count from 1 to 16, one count for each thread.large: 2 threads count to 100,000 at the same time. Each thread changes only its own counter, so the counts do not need a lock or an atomic operation. A shared counter with no lock would be a data race.
Pitfalls
- Thread pools keep the values. A pool reuses its threads, so a value that one task leaves in a thread-local variable is still there for the next task on that thread. JEP 506 warns that such a value "could, if not properly cleared, accidentally leak into an unrelated task".14 The solutions start a new thread for each count, so each counter starts at 0. On a pool, reset the value at the start of each task, or call Java
remove(), which "Removes the current thread's value for this thread-local variable".2
In Python, a pool of one thread shows the leak. Each task reads the counter and adds 1, and each task after the first sees the count of the tasks before it:
import threading
from concurrent.futures import ThreadPoolExecutor
local = threading.local()
def task(name):
seen = getattr(local, "counter", 0)
local.counter = seen + 1
return f"{name} starts at {seen}"
with ThreadPoolExecutor(max_workers=1) as pool:
for line in pool.map(task, ["task 1", "task 2", "task 3"]):
print(line)
task 1 starts at 0
task 2 starts at 1
task 3 starts at 2
- An initializer on
[ThreadStatic]. Do not give a[ThreadStatic]field an initial value, as in[ThreadStatic] static int counter = 1;. That initialization "occurs only once, when the class constructor executes, and therefore affects only one thread".3 UseThreadLocal<T>with a factory for a value that is not the default.10 - Reading the value after the thread ends. The value belongs to its thread. In C++, its storage lasts only as long as the thread,6 and in Java, "after a thread goes away, all of its copies of thread-local instances are subject to garbage collection".2 Copy the value to a result while the thread runs, as the solutions do.
- Reading the value on the wrong thread.
current()on the caller returns the counter of the caller, not of a thread that it started. The caller gets the counters of the other threads only through the results. - Async code. One thread can run many async tasks, and one task can continue on another thread after an
await. Use async-local storage for values that must follow a task.1213
Related tasks
- Thread-local storage explains the idea, with examples in more languages.
- Thread-Specific Storage is the design pattern behind this task.
- Thread confinement keeps data on one thread, so it needs no lock.
- Start a thread and Wait for threads to finish start and join the threads.
- Run tasks on a thread pool runs jobs on threads that a pool reuses, where thread-local values outlive a job.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-thread-local-storage/.
"""Count on a thread-local counter in one thread for each count, with no lock and no shared counter."""
import threading
# One object for all threads. Its attributes have a separate value in each thread.
_local = threading.local()
def bump() -> int:
# A new thread sees no attribute yet, so its counter starts at 0.
_local.counter = getattr(_local, "counter", 0) + 1
return _local.counter
def current() -> int:
return getattr(_local, "counter", 0)
def count_per_thread(counts: list[int]) -> list[int]:
results = [0] * len(counts)
def work(i: int) -> None:
for _ in range(counts[i]):
bump()
# Each thread writes only its own slot of the list.
results[i] = current()
threads = [threading.Thread(target=work, args=(i,)) for i in range(len(counts))]
for t in threads:
t.start()
for t in threads:
t.join()
return results
test_tls.py 41 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/use-thread-local-storage/.
import threading
import pytest
from tls import bump, count_per_thread, current
CASES = {
"three-threads": [1, 2, 3],
"uneven": [10, 0, 5, 1000],
"empty": [],
"zero": [0],
"one-thread": [7],
"equal-counts": [100, 100, 100, 100],
"many-threads": list(range(1, 17)),
"large": [100000, 100000],
}
@pytest.mark.parametrize("name", CASES)
def test_count_per_thread(name):
counts = CASES[name]
assert count_per_thread(counts) == counts
def test_caller_counter_does_not_change():
# Run in a new thread, so that other tests on the main thread do not matter.
seen = []
def caller():
for _ in range(3):
bump()
count_per_thread([5, 6])
seen.append(current())
t = threading.Thread(target=caller)
t.start()
t.join()
assert seen == [3]
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
// Count on a thread-local counter in one thread for each count, with no lock and no shared counter.
#include "tls.hpp"
#include <cstddef>
#include <thread>
namespace tls {
namespace {
// Each thread has its own copy of this variable. The copy is made when the thread starts
// and destroyed when the thread ends.
thread_local std::int32_t counter = 0;
} // namespace
std::int32_t bump() { return ++counter; }
std::int32_t current() { return counter; }
std::vector<std::int32_t> count_per_thread(const std::vector<std::int32_t>& counts) {
std::vector<std::int32_t> results(counts.size(), 0);
{
std::vector<std::jthread> threads;
threads.reserve(counts.size());
for (std::size_t i = 0; i < counts.size(); i++) {
threads.emplace_back([&counts, &results, i] {
for (std::int32_t k = 0; k < counts[i]; k++) {
bump();
}
// Each thread writes only its own element. The join makes the write visible to the caller.
results[i] = current();
});
}
} // The jthread destructors join every thread here.
return results;
}
} // namespace tls
tls.hpp 21 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
#pragma once
#include <cstdint>
#include <vector>
namespace tls {
// Adds 1 to the counter of the current thread and returns the new value.
std::int32_t bump();
// Returns the counter of the current thread.
std::int32_t current();
// Starts one thread for each count and returns the final counter of each thread, in order.
// Throws std::system_error if a thread cannot be started.
std::vector<std::int32_t> count_per_thread(const std::vector<std::int32_t>& counts);
} // namespace tls
test_tls.cpp 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
#include "tls.hpp"
#include <cstdint>
#include <iostream>
#include <numeric>
#include <string_view>
#include <thread>
#include <vector>
static int failures = 0;
static void check(std::string_view name, const std::vector<std::int32_t>& counts) {
if (tls::count_per_thread(counts) != counts) {
std::cerr << "case " << name << " failed\n";
failures++;
}
}
int main() {
check("three-threads", {1, 2, 3});
check("uneven", {10, 0, 5, 1000});
check("empty", {});
check("zero", {0});
check("one-thread", {7});
check("equal-counts", {100, 100, 100, 100});
std::vector<std::int32_t> many(16);
std::iota(many.begin(), many.end(), 1);
check("many-threads", many);
check("large", {100000, 100000});
// Run in a new thread, so that the counter of the main thread does not matter.
std::int32_t seen = -1;
std::thread caller([&seen] {
for (int k = 0; k < 3; k++) {
tls::bump();
}
tls::count_per_thread({5, 6});
seen = tls::current();
});
caller.join();
if (seen != 3) {
std::cerr << "case caller-counter failed: got " << seen << ", want 3\n";
failures++;
}
if (failures == 0) {
std::cout << "all tests passed\n";
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
// Count on a thread-local counter in one thread for each count, with no lock and no shared counter.
public final class Tls {
private Tls() {}
// One ThreadLocal for all threads. Each thread gets its own copy, which starts at 0.
private static final ThreadLocal<Integer> COUNTER = ThreadLocal.withInitial(() -> 0);
static int bump() {
int next = COUNTER.get() + 1;
COUNTER.set(next);
return next;
}
static int current() {
return COUNTER.get();
}
public static int[] countPerThread(int[] counts) throws InterruptedException {
int[] results = new int[counts.length];
Thread[] threads = new Thread[counts.length];
for (int i = 0; i < counts.length; i++) {
int index = i;
threads[i] =
Thread.ofPlatform()
.start(
() -> {
for (int k = 0; k < counts[index]; k++) {
bump();
}
// Each thread writes only its own slot. join() makes the write visible to the caller.
results[index] = current();
});
}
for (Thread t : threads) {
t.join();
}
return results;
}
}
TlsTest.java 54 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertEquals;
import java.util.stream.IntStream;
import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;
class TlsTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("three-threads", new int[] {1, 2, 3}),
Arguments.of("uneven", new int[] {10, 0, 5, 1000}),
Arguments.of("empty", new int[] {}),
Arguments.of("zero", new int[] {0}),
Arguments.of("one-thread", new int[] {7}),
Arguments.of("equal-counts", new int[] {100, 100, 100, 100}),
Arguments.of("many-threads", IntStream.rangeClosed(1, 16).toArray()),
Arguments.of("large", new int[] {100000, 100000}));
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void countPerThread(String name, int[] counts) throws InterruptedException {
assertArrayEquals(counts, Tls.countPerThread(counts), name);
}
@Test
void callerCounterDoesNotChange() throws InterruptedException {
int[] seen = new int[1];
// Run in a new thread, so that other tests on this thread do not matter.
Thread caller =
Thread.ofPlatform()
.start(
() -> {
for (int k = 0; k < 3; k++) {
Tls.bump();
}
try {
Tls.countPerThread(new int[] {5, 6});
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
seen[0] = Tls.current();
});
caller.join();
assertEquals(3, seen[0]);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
// Count on a thread-local counter in one thread for each count, with no lock and no shared counter.
#include "tls.h"
#include <pthread.h>
// Each thread has its own copy of this variable, and each copy starts at 0.
// C23 also accepts the spelling thread_local.
static _Thread_local int32_t counter = 0;
int32_t tls_bump(void) {
return ++counter;
}
int32_t tls_current(void) {
return counter;
}
struct job {
int32_t count;
int32_t result;
};
static void *work(void *arg) {
struct job *job = arg;
for (int32_t k = 0; k < job->count; k++) {
tls_bump();
}
// Each thread writes only its own job. pthread_join makes the write visible to the caller.
job->result = tls_current();
return NULL;
}
bool count_per_thread(const int32_t counts[], size_t n, int32_t out[]) {
if (n > TLS_MAX_THREADS) {
return false;
}
pthread_t threads[TLS_MAX_THREADS];
struct job jobs[TLS_MAX_THREADS];
size_t started = 0;
bool ok = true;
for (; started < n; started++) {
jobs[started] = (struct job){.count = counts[started], .result = 0};
if (pthread_create(&threads[started], NULL, work, &jobs[started]) != 0) {
ok = false;
break;
}
}
// Join every thread that started, also after an error.
for (size_t i = 0; i < started; i++) {
pthread_join(threads[i], NULL);
}
if (!ok) {
return false;
}
for (size_t i = 0; i < n; i++) {
out[i] = jobs[i].result;
}
return true;
}
tls.h 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
#ifndef TLS_H
#define TLS_H
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#define TLS_MAX_THREADS 16
// Adds 1 to the counter of the current thread and returns the new value.
int32_t tls_bump(void);
// Returns the counter of the current thread.
int32_t tls_current(void);
// Starts one thread for each of the n counts. Thread i calls tls_bump counts[i] times and writes
// its final counter to out[i]. Returns false if n is more than TLS_MAX_THREADS or a thread does not start.
bool count_per_thread(const int32_t counts[], size_t n, int32_t out[]);
#endif
test_tls.c 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
#include "tls.h"
#include <pthread.h>
#include <stdio.h>
static int failures = 0;
static void check(const char *name, const int32_t counts[], size_t n) {
int32_t got[TLS_MAX_THREADS] = {0};
if (!count_per_thread(counts, n, got)) {
fprintf(stderr, "case %s failed: the threads did not start\n", name);
failures++;
return;
}
for (size_t i = 0; i < n; i++) {
if (got[i] != counts[i]) {
fprintf(stderr, "case %s failed at %zu: got %d, want %d\n", name, i, got[i], counts[i]);
failures++;
return;
}
}
}
static void *caller(void *arg) {
int32_t *seen = arg;
for (int k = 0; k < 3; k++) {
tls_bump();
}
int32_t out[2];
count_per_thread((int32_t[]){5, 6}, 2, out);
*seen = tls_current();
return NULL;
}
int main(void) {
check("three-threads", (int32_t[]){1, 2, 3}, 3);
check("uneven", (int32_t[]){10, 0, 5, 1000}, 4);
check("empty", NULL, 0);
check("zero", (int32_t[]){0}, 1);
check("one-thread", (int32_t[]){7}, 1);
check("equal-counts", (int32_t[]){100, 100, 100, 100}, 4);
int32_t many[16];
for (int i = 0; i < 16; i++) {
many[i] = i + 1;
}
check("many-threads", many, 16);
check("large", (int32_t[]){100000, 100000}, 2);
// Run in a new thread, so that the counter of the main thread does not matter.
int32_t seen = -1;
pthread_t t;
if (pthread_create(&t, NULL, caller, &seen) != 0 || pthread_join(t, NULL) != 0 || seen != 3) {
fprintf(stderr, "case caller-counter failed: got %d, want 3\n", seen);
failures++;
}
int32_t out[TLS_MAX_THREADS + 1];
int32_t too_many[TLS_MAX_THREADS + 1] = {0};
if (count_per_thread(too_many, TLS_MAX_THREADS + 1, out)) {
fprintf(stderr, "case too-many failed: want false\n");
failures++;
}
if (failures == 0) {
printf("all tests passed\n");
}
return failures == 0 ? 0 : 1;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
// Count on a thread-local counter in one thread for each count, with no lock and no shared counter.
using System.Threading;
public static class Tls
{
// Each thread has its own copy of this static field. Do not give it an initial value here:
// that would set the copy of one thread only. The copy of every other thread starts at 0.
[ThreadStatic]
private static int counter;
public static int Bump() => ++counter;
public static int Current() => counter;
public static int[] CountPerThread(int[] counts)
{
var results = new int[counts.Length];
var threads = new Thread[counts.Length];
for (int i = 0; i < counts.Length; i++)
{
int index = i;
threads[i] = new Thread(() =>
{
for (int k = 0; k < counts[index]; k++)
{
Bump();
}
// Each thread writes only its own slot. Join makes the write visible to the caller.
results[index] = Current();
});
threads[i].Start();
}
foreach (var t in threads)
{
t.Join();
}
return results;
}
}
TlsTests.cs 48 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
using System.Linq;
using System.Threading;
using Xunit;
public sealed class TlsTests
{
public static TheoryData<string, int[]> Cases => new()
{
{ "three-threads", new[] { 1, 2, 3 } },
{ "uneven", new[] { 10, 0, 5, 1000 } },
{ "empty", new int[] { } },
{ "zero", new[] { 0 } },
{ "one-thread", new[] { 7 } },
{ "equal-counts", new[] { 100, 100, 100, 100 } },
{ "many-threads", Enumerable.Range(1, 16).ToArray() },
{ "large", new[] { 100000, 100000 } },
};
[Theory]
[MemberData(nameof(Cases))]
public void CountPerThread(string name, int[] counts)
{
Assert.NotNull(name);
Assert.Equal(counts, Tls.CountPerThread(counts));
}
[Fact]
public void CallerCounterDoesNotChange()
{
int seen = -1;
// Run in a new thread, so that other tests on this thread do not matter.
var caller = new Thread(() =>
{
for (int k = 0; k < 3; k++)
{
Tls.Bump();
}
Tls.CountPerThread(new[] { 5, 6 });
seen = Tls.Current();
});
caller.Start();
caller.Join();
Assert.Equal(3, seen);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
// Count on a per-thread counter in one worker thread for each count, with no lock and no shared counter.
import { isMainThread, parentPort, Worker, workerData } from "node:worker_threads";
// Each thread loads its own copy of this module, so each thread has its own counter.
let counter = 0;
export function bump() {
counter += 1;
return counter;
}
export function current() {
return counter;
}
if (!isMainThread) {
// This is a worker: count, then send the counter of this thread back.
for (let k = 0; k < workerData; k++) bump();
parentPort.postMessage(current());
}
function runWorker(count) {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL(import.meta.url), { workerData: count });
worker.once("message", resolve);
worker.once("error", reject);
});
}
// Returns a promise of the final counter of each worker, in the order of counts.
export async function countPerThread(counts) {
return Promise.all(counts.map(runWorker));
}
tls.test.js 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { bump, countPerThread, current } from "./tls.js";
const cases = [
["three-threads", [1, 2, 3]],
["uneven", [10, 0, 5, 1000]],
["empty", []],
["zero", [0]],
["one-thread", [7]],
["equal-counts", [100, 100, 100, 100]],
["many-threads", Array.from({ length: 16 }, (_, i) => i + 1)],
["large", [100000, 100000]],
];
for (const [name, counts] of cases) {
test(name, async () => {
assert.deepEqual(await countPerThread(counts), counts);
});
}
test("the counter of the main thread does not change", async () => {
const before = current();
for (let k = 0; k < 3; k++) bump();
await countPerThread([5, 6]);
assert.equal(current(), before + 3);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
// Count on a per-thread counter in one worker thread for each count, with no lock and no shared counter.
import { isMainThread, parentPort, Worker, workerData } from "node:worker_threads";
// Each thread loads its own copy of this module, so each thread has its own counter.
let counter = 0;
export function bump(): number {
counter += 1;
return counter;
}
export function current(): number {
return counter;
}
if (!isMainThread) {
// This is a worker: count, then send the counter of this thread back.
for (let k = 0; k < (workerData as number); k++) bump();
parentPort!.postMessage(current());
}
function runWorker(count: number): Promise<number> {
return new Promise((resolve, reject) => {
const worker = new Worker(new URL(import.meta.url), { workerData: count });
worker.once("message", resolve);
worker.once("error", reject);
});
}
// Returns a promise of the final counter of each worker, in the order of counts.
export async function countPerThread(counts: number[]): Promise<number[]> {
return Promise.all(counts.map(runWorker));
}
tls.test.ts 31 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { bump, countPerThread, current } from "./tls.ts";
const cases: [string, number[]][] = [
["three-threads", [1, 2, 3]],
["uneven", [10, 0, 5, 1000]],
["empty", []],
["zero", [0]],
["one-thread", [7]],
["equal-counts", [100, 100, 100, 100]],
["many-threads", Array.from({ length: 16 }, (_, i) => i + 1)],
["large", [100000, 100000]],
];
for (const [name, counts] of cases) {
test(name, async () => {
assert.deepEqual(await countPerThread(counts), counts);
});
}
test("the counter of the main thread does not change", async () => {
const before = current();
for (let k = 0; k < 3; k++) bump();
await countPerThread([5, 6]);
assert.equal(current(), before + 3);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
// Package tls gives each goroutine its own counter. Go has no thread-local or goroutine-local
// storage, so each goroutine makes its counter and passes it to the code that uses it.
package tls
import "sync"
// Counter belongs to one goroutine, so it needs no lock.
type Counter struct {
n int
}
// Bump adds 1 to the counter and returns the new value.
func (c *Counter) Bump() int {
c.n++
return c.n
}
// Current returns the value of the counter.
func (c *Counter) Current() int {
return c.n
}
// CountPerThread starts one goroutine for each count and returns the final counter of each goroutine, in order.
func CountPerThread(counts []int) []int {
results := make([]int, len(counts))
var wg sync.WaitGroup
for i, n := range counts {
wg.Add(1)
go func() {
defer wg.Done()
// The counter is a local variable of this goroutine. Code that needs it gets it as a value.
var c Counter
for range n {
c.Bump()
}
// Each goroutine writes only its own element. Wait makes the write visible to the caller.
results[i] = c.Current()
}()
}
wg.Wait()
return results
}
tls_test.go 45 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
package tls
import (
"slices"
"testing"
)
func TestCountPerThread(t *testing.T) {
var many []int
for n := 1; n <= 16; n++ {
many = append(many, n)
}
cases := []struct {
name string
counts []int
}{
{"three-threads", []int{1, 2, 3}},
{"uneven", []int{10, 0, 5, 1000}},
{"empty", []int{}},
{"zero", []int{0}},
{"one-thread", []int{7}},
{"equal-counts", []int{100, 100, 100, 100}},
{"many-threads", many},
{"large", []int{100000, 100000}},
}
for _, c := range cases {
if got := CountPerThread(c.counts); !slices.Equal(got, c.counts) {
t.Errorf("case %s: got %v, want %v", c.name, got, c.counts)
}
}
}
func TestCallerCounterDoesNotChange(t *testing.T) {
var c Counter
for range 3 {
c.Bump()
}
CountPerThread([]int{5, 6})
if got := c.Current(); got != 3 {
t.Errorf("got %d, want 3", got)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
//! Counts on a thread-local counter in one thread for each count, with no lock and no shared counter.
use std::cell::Cell;
use std::thread;
thread_local! {
// Each thread gets its own Cell, which starts at 0. A const initializer needs no lazy setup.
static COUNTER: Cell<u32> = const { Cell::new(0) };
}
/// Adds 1 to the counter of the current thread and returns the new value.
pub fn bump() -> u32 {
COUNTER.with(|c| {
c.set(c.get() + 1);
c.get()
})
}
/// Returns the counter of the current thread.
pub fn current() -> u32 {
COUNTER.with(Cell::get)
}
/// Starts one thread for each count and returns the final counter of each thread, in order.
/// Panics if a thread cannot be created.
pub fn count_per_thread(counts: &[u32]) -> Vec<u32> {
// The scope joins every thread before it returns, so the threads can borrow counts.
thread::scope(|s| {
let handles: Vec<_> = counts
.iter()
.map(|&n| {
s.spawn(move || {
for _ in 0..n {
bump();
}
current()
})
})
.collect();
handles
.into_iter()
.map(|h| h.join().expect("no thread panicked"))
.collect()
})
}
tests/tls_test.rs 37 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/use-thread-local-storage/.
use algo_use_thread_local_storage::{bump, count_per_thread, current};
use std::thread;
#[test]
fn cases() {
let cases: Vec<(&str, Vec<u32>)> = vec![
("three-threads", vec![1, 2, 3]),
("uneven", vec![10, 0, 5, 1000]),
("empty", vec![]),
("zero", vec![0]),
("one-thread", vec![7]),
("equal-counts", vec![100, 100, 100, 100]),
("many-threads", (1..=16).collect()),
("large", vec![100000, 100000]),
];
for (name, counts) in cases {
assert_eq!(count_per_thread(&counts), counts, "case {name}");
}
}
#[test]
fn caller_counter_does_not_change() {
// Run in a new thread, so that other tests on this thread do not matter.
let seen = thread::spawn(|| {
for _ in 0..3 {
bump();
}
count_per_thread(&[5, 6]);
current()
})
.join()
.expect("the caller did not panic");
assert_eq!(seen, 3);
}
References
- The Python Standard Library, threading, Thread-local data
- Java SE 21 API, java.lang.ThreadLocal, class description; withInitial; remove()
- Microsoft Learn, ThreadStaticAttribute class, Remarks
- Rust standard library, macro std::thread_local, Syntax
- Rust standard library, struct std::thread::LocalKey, Initialization and Destruction; impl LocalKey<Cell<T>>
- cppreference, Storage duration, Thread storage duration
- Wikipedia, Thread-local storage, C and C++
- Go FAQ, Why is there no goroutine ID?
- Node.js documentation, Worker threads, worker_threads.isMainThread; Class Worker
- Microsoft Learn, ThreadLocal<T> class, class description; Values
- POSIX.1-2024, pthread_key_create, DESCRIPTION
- Node.js documentation, Asynchronous context tracking, Introduction
- Python documentation, contextvars, introduction
- JEP 506: Scoped Values, Problems with thread-local variables
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 |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
Tag QEF7A4 Edit this page History Report an error Markdown