Conceptcore
Thread
Also called thread of execution, thread of control, OS thread.
A thread is one sequence of execution inside a process. The threads of a process share its memory, and each thread has its own stack, so several threads can run at the same time.
- Applies to
- core-languages
Idea
A process is a program in execution, with its own memory.1 A thread is one sequence of execution inside a process, a thread of control. A process starts with one thread, and that thread can start more. All threads of a process share its address space: the heap, the global variables and the open files.23 Each thread has its own stack and its own position in the code.4 The C standard says that a program can have more than one thread of execution running concurrently.5
Threads have two main uses. On a computer with several cores, threads can compute parts of one job in parallel. On any computer, one thread can wait for a disk, a network or a user while other threads keep working. In Python, the module threading starts OS threads. Here, three threads each fill their own slot of a list. The main thread waits for all of them with join(), and then it reads the list.
import threading
def square(results, index):
results[index] = index * index
results = [None] * 3
workers = [threading.Thread(target=square, args=(results, i)) for i in range(3)]
for worker in workers:
worker.start()
print("started:", len(workers))
for worker in workers:
worker.join()
print("results:", results)
print("alive after join:", any(w.is_alive() for w in workers))
started: 3
results: [0, 1, 4]
alive after join: False
The threads run in an order that the program does not control. The main thread reads results only after each join() has returned, so the output is the same on every run. Threads that change shared data at the same time cause Data race. A lock gives Mutual exclusion, and a cycle of locks can cause a Deadlock. Threads can also send each other values through Channel and share no data at all.
How it works
Start, join and detach
A program starts a thread with a function to run and, often, an argument. The POSIX function pthread_create makes a thread that runs start_routine with one void * argument.6 The thread ends when the function returns. Another thread can then join it. pthread_join suspends the caller until the target thread ends, and it stores the value that the thread returned.7
Join does two jobs. It waits, and it makes the work of the thread visible to the joiner. In C++, the end of the thread synchronizes with the return of join().8 Every write that the thread made before it ended is visible after join(). This is why the examples on this page can read the results without a lock.
A thread that nobody will join is detached. Its resources go back to the system when it ends. POSIX says that an application must join or detach each joinable thread, because otherwise the system cannot reclaim the storage of the thread.7 On Linux, a thread is joinable by default.9 In C++, detach() lets the thread run on with no handle.8 In Rust, dropping the JoinHandle detaches the thread.10
Languages return the result of a thread in different ways.
| Language | Start | Wait | Result of the thread |
|---|---|---|---|
| C | pthread_create |
pthread_join |
a void * that the thread returns7 |
| C++ | std::thread, std::jthread |
join() |
none; std::async returns a std::future11 |
| Rust | thread::spawn |
JoinHandle::join |
Result<T>, an Err when the thread panicked10 |
| Java | Thread.ofPlatform().start, Thread.ofVirtual().start |
join() |
none; join() returns void12 |
| Python | Thread(target=f).start() |
join() |
none; join() returns None3 |
| C# | new Thread(f).Start() |
Join() |
none; Task.Run returns a Task<TResult>13 |
| Go | go f() |
sync.WaitGroup |
none; the results of f are discarded2 |
| JavaScript | new Worker |
the exit event |
a message from postMessage14 |
When no result comes back through the join, each thread writes to its own location, such as its own element of an array. A future is a handle that holds the result. In Python, Future.result() waits for the call and returns its value.15
Daemon threads and the end of the program
The rules for the end of a program differ, and they decide whether a running thread finishes its work.
- In Go, the program exits when
mainreturns. It does not wait for other goroutines.16 - In Rust, the program shuts down when the main thread ends, even if other threads are still running.10
- In Java, the shutdown sequence begins when all started non-daemon threads have ended. Virtual threads are always daemon threads.12
- In Python, the interpreter waits for non-daemon threads. Daemon threads stop abruptly at shutdown, and their resources may not be released.3
- In C#, a background thread does not keep the process alive. At the end of the process, the runtime stops background threads with no exception.17
One to one, many to one, many to many
A thread that the program sees must run on a thread of the operating system kernel. Three mappings exist.
1:1 M:1 M:N
T1 T2 T3 T1 T2 T3 T1 T2 T3 T4 T5 T6
| | | \ | / \ | / \ | /
K1 K2 K3 K1 K1 K2
T = a thread of the program K = a kernel thread
In the 1:1 model, each program thread is one kernel thread. The POSIX thread libraries of Linux use it.18 A Rust program is a collection of native OS threads.10 Java platform threads are typically mapped 1:1 to kernel threads.12 The kernel schedules each thread, so a thread that blocks in a system call stops only itself.
In the M:1 model, a runtime library runs all program threads on one kernel thread. These are often called green threads. Early versions of Java had green threads that shared one OS thread, and platform threads later outperformed them.19 A pure user-level implementation cannot use more than one processor.18
In the M:N model, a runtime schedules many program threads onto a smaller number of kernel threads. Java virtual threads use this model.19 The Go runtime multiplexes goroutines onto a set of OS threads. When a goroutine blocks in a system call, the runtime moves the other goroutines of that OS thread to another runnable thread.20
M:N needs two schedulers, one in the runtime and one in the kernel. The designers of the Native POSIX Thread Library for Linux considered M:N. They wrote that the two schedulers must collaborate, for example through scheduler activations, or performance suffers. The kernel developers chose 1:1 for Linux.18
Virtual threads in Java
A virtual thread is a java.lang.Thread that the JDK schedules, not the OS. The JDK scheduler is a work-stealing ForkJoinPool, and by default its parallelism is the number of available processors. The scheduler mounts a virtual thread on a platform thread, its carrier, to run it. When the virtual thread blocks, for example in I/O, the JDK unmounts it and the carrier runs another virtual thread.19
The scheduler does not use time sharing for virtual threads. It does not preempt a virtual thread that has used a fixed quantity of CPU time.19 A virtual thread is pinned when it cannot unmount while it blocks. Then it holds its carrier, for example during a call to native code.19 JEP 491 removed nearly all cases of pinning inside synchronized code.21
The global interpreter lock in Python
The default build of CPython has a global interpreter lock (GIL). The GIL makes sure that only one thread executes Python bytecode at a time.22 Python threads are still OS threads, and the GIL is always released during I/O.22 The threading documentation therefore recommends threads for I/O-bound tasks, and processes for CPU-bound work.3
PEP 703 made the GIL optional.23 A free-threaded build of CPython is configured with --disable-gil before compilation.22 To work without the GIL, the free-threaded build uses biased reference counting, immortal objects, deferred reference counting and per-object locks. It also uses the mimalloc allocator.23
A program can ask which build runs it. In a free-threaded build, the output of python -VV contains "free-threading build", and sysconfig.get_config_var("Py_GIL_DISABLED") is 1. The function sys._is_gil_enabled() tells whether the GIL is active at run time.2425 A free-threaded build can enable the GIL again. The environment variable PYTHON_GIL and the option -X gil do this. The interpreter also enables the GIL, with a warning, when it imports a C extension module that is not marked as safe without it.24 This run uses the default build.
import sys
import sysconfig
print("free-threaded build:", sysconfig.get_config_var("Py_GIL_DISABLED") == 1)
print("GIL enabled now:", sys._is_gil_enabled())
free-threaded build: False
GIL enabled now: True
In languages
| Language | Verdict | Note |
|---|---|---|
| Python | Standard library | |
| C++ | Standard library | |
| Java | Standard library | |
| C | Standard library | |
| C# | Standard library | |
| JavaScript | Standard library | |
| TypeScript | Standard library | |
| Go | Native | |
| Rust | Standard library | |
| Kotlin | Standard library | |
| SQL | Does not apply | A query states a result, and the database engine decides how many threads compute it. |
| Bash | Absent | The shell has no threads; each command in the background is a separate process. Alternative: Background processes started with & and waited for with wait. |
| PowerShell | Standard library | |
| HTML | Does not apply | Markup has no threads of control. |
| CSS | Does not apply | Style rules have no threads of control. |
| Regular expressions | Does not apply | A pattern has no threads of control. |
The example files show four threads that each sum a quarter of the numbers 0 to 999, and a join of all four. The table gives the verdict for each tier 1 language.
| Language | Verdict | Form |
|---|---|---|
| Python | stdlib | threading.Thread; one thread at a time runs bytecode in the default build |
| JavaScript | stdlib | node:worker_threads in Node.js; each worker has its own event loop |
| TypeScript | stdlib | as JavaScript |
| Java | stdlib | java.lang.Thread: platform threads (1:1) and virtual threads (M:N) |
| C | stdlib | POSIX threads; ISO C <threads.h> is optional |
| C++ | stdlib | std::thread, std::jthread |
| C# | stdlib | System.Threading.Thread; the thread pool through Task.Run |
| Go | native | the go statement; goroutines (M:N) |
| Rust | stdlib | std::thread::spawn, std::thread::scope |
| Kotlin | stdlib | kotlin.concurrent.thread over java.lang.Thread |
| PowerShell | stdlib | ForEach-Object -Parallel on a pool of runspaces |
| Bash | absent | background processes with & and wait |
| SQL | n/a | the database engine decides how many threads run a query |
| Regex | n/a | a pattern has no threads of control |
| HTML/CSS | n/a | markup and style rules have no threads of control |
ISO C defines threads in <threads.h>, but the header is optional. An implementation that does not provide it defines the macro __STDC_NO_THREADS__.5 The C library of macOS has no <threads.h>, so the C example uses POSIX threads.
JavaScript has no threads that share a heap. A Node.js worker is an independent JavaScript thread with its own event loop, and it exchanges messages with the main thread.14 Workers help with CPU-bound work. For I/O, Async/await on one thread is the usual form.
In Bash, a command that ends with & runs asynchronously in a subshell, and the shell does not wait for it.26 The subshell is a separate process, not a thread. PowerShell runs each script block of ForEach-Object -Parallel on its own thread, in a runspace from a pool of five by default.27 The Kotlin function thread makes and starts a java.lang.Thread, with named arguments for the name and the daemon flag.28
import sys
import threading
def partial_sum(results, index, start, stop):
results[index] = sum(range(start, stop))
results = [0] * 4
workers = [
threading.Thread(target=partial_sum, args=(results, i, i * 250, (i + 1) * 250))
for i in range(4)
]
for worker in workers:
worker.start()
for worker in workers:
worker.join()
print(results)
print("total:", sum(results))
print("daemon:", workers[0].daemon)
print("GIL enabled:", sys._is_gil_enabled())
[31125, 93625, 156125, 218625]
total: 499500
daemon: False
GIL enabled: True
- Verdict: stdlib.
threading.Threadruns a function on an OS thread.join()waits for it to end. - A thread cannot return a value through
join(), which returnsNone. Each thread writes its result to its own slot of a list.concurrent.futures.ThreadPoolExecutorreturns results through futures instead. - In the default build of CPython, the global interpreter lock lets one thread at a time run Python bytecode. The free-threaded build has no GIL, and there
sys._is_gil_enabled()returnsFalse. - A thread is not a daemon unless you pass
daemon=True. The interpreter waits for all non-daemon threads before it exits.
#include <numeric>
#include <print>
#include <thread>
#include <vector>
int main() {
std::vector<long> results(4);
{
std::vector<std::jthread> workers;
for (int i = 0; i < 4; ++i) {
workers.emplace_back([&results, i] {
long sum = 0;
for (long n = i * 250; n < (i + 1) * 250; ++n) {
sum += n;
}
results[i] = sum;
});
}
}
std::println("{}", results);
std::println("total: {}", std::accumulate(results.begin(), results.end(), 0L));
bool ran = false;
std::thread worker([&ran] { ran = true; });
std::println("joinable before join: {}", worker.joinable());
worker.join();
std::println("ran: {}, joinable after join: {}", ran, worker.joinable());
}
[31125, 93625, 156125, 218625]
total: 499500
joinable before join: true
ran: true, joinable after join: false
- Verdict: stdlib.
std::threadruns a callable on another thread. The end of the thread synchronizes with the return ofjoin(), somainsees each result. std::jthreadjoins in its destructor. The block around the workers ends only when all four threads have ended.- A
std::threadthat is still joinable when it is destroyed callsstd::terminate(see Pitfalls). Calljoin()ordetach()first. - The callable cannot return a value through
join(). Write to a captured location, or usestd::asyncand astd::future.
import java.time.Duration;
import java.util.Arrays;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class Main {
public static void main(String[] args) throws InterruptedException {
long[] results = new long[4];
Thread[] workers = new Thread[4];
for (int i = 0; i < 4; i++) {
int index = i;
workers[i] = Thread.ofPlatform().start(() -> {
long sum = 0;
for (long n = index * 250L; n < (index + 1) * 250L; n++) {
sum += n;
}
results[index] = sum;
});
}
for (Thread worker : workers) {
worker.join();
}
System.out.println(Arrays.toString(results));
System.out.println("platform: virtual=" + workers[0].isVirtual() + " daemon=" + workers[0].isDaemon());
Thread virtual = Thread.ofVirtual().unstarted(() -> {});
System.out.println("virtual: virtual=" + virtual.isVirtual() + " daemon=" + virtual.isDaemon());
AtomicInteger done = new AtomicInteger();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(10));
return done.incrementAndGet();
});
}
}
System.out.println("virtual threads finished: " + done.get());
}
}
[31125, 93625, 156125, 218625]
platform: virtual=false daemon=false
virtual: virtual=true daemon=true
virtual threads finished: 10000
- Verdict: stdlib.
java.lang.Threadmakes platform threads, which wrap OS threads, and virtual threads, which the JDK runs on a few carrier threads (M:N). join()waits for the thread. ARunnablereturns nothing, so each thread writes its own array element.- A virtual thread is always a daemon thread. Closing the executor waits for all 10,000 tasks.
- A sleeping virtual thread frees its carrier for other tasks.
#include <pthread.h>
#include <stdio.h>
struct job {
long start, stop, sum;
};
static void *partial_sum(void *arg) {
struct job *job = arg;
for (long n = job->start; n < job->stop; n++) {
job->sum += n;
}
return &job->sum;
}
int main(void) {
pthread_t threads[4];
struct job jobs[4];
for (int i = 0; i < 4; i++) {
jobs[i] = (struct job){i * 250L, (i + 1) * 250L, 0};
if (pthread_create(&threads[i], NULL, partial_sum, &jobs[i]) != 0) {
return 1;
}
}
long total = 0;
for (int i = 0; i < 4; i++) {
void *result;
pthread_join(threads[i], &result);
printf("thread %d: %ld\n", i, *(long *)result);
total += *(long *)result;
}
printf("total: %ld\n", total);
return 0;
}
thread 0: 31125
thread 1: 93625
thread 2: 156125
thread 3: 218625
total: 499500
- Verdict: stdlib. This example uses POSIX threads. ISO C defines
<threads.h>, but it is optional: an implementation that defines__STDC_NO_THREADS__does not provide it, and the macOS C library is one such implementation. pthread_createtakes a function of typevoid *(void *)and one argument. A struct carries the input and the result.pthread_joinwaits for the thread and stores its return value through the second argument. The pointer must point to memory that is still alive, here an element ofjobsinmain.- Join or detach every thread. Otherwise the system cannot reclaim its storage.
using System.Threading;
long[] results = new long[4];
var workers = new Thread[4];
for (int i = 0; i < 4; i++)
{
int index = i;
workers[i] = new Thread(() =>
{
long sum = 0;
for (long n = index * 250L; n < (index + 1) * 250L; n++)
{
sum += n;
}
results[index] = sum;
});
}
bool background = workers[0].IsBackground;
foreach (var worker in workers)
{
worker.Start();
}
foreach (var worker in workers)
{
worker.Join();
}
Console.WriteLine(string.Join(", ", results));
Console.WriteLine($"background: {background}");
var slow = new Thread(() => Thread.Sleep(5000)) { IsBackground = true };
slow.Start();
bool finished = slow.Join(TimeSpan.FromMilliseconds(100));
Console.WriteLine($"finished within 100 ms: {finished}");
31125, 93625, 156125, 218625
background: False
finished within 100 ms: False
- Verdict: stdlib.
System.Threading.Threadwraps an OS thread.Start()runs the delegate, andJoin()waits for it to end. - A thread is a foreground thread by default. The process does not end while a foreground thread runs. The
slowthread is a background thread, so the process ends without waiting for it. Join(TimeSpan)returnsfalsewhen the time runs out first. The thread keeps running.- For short jobs,
Task.Runqueues the work to the thread pool instead of making a dedicated thread.
import { Worker } from "node:worker_threads";
const source = `
const { parentPort, workerData } = require("node:worker_threads");
let sum = 0;
for (let n = workerData.start; n < workerData.stop; n++) sum += n;
parentPort.postMessage(sum);
`;
function partialSum(start, stop) {
return new Promise((resolve, reject) => {
const worker = new Worker(source, { eval: true, workerData: { start, stop } });
worker.once("message", resolve);
worker.once("error", reject);
});
}
const jobs = [0, 1, 2, 3].map((i) => partialSum(i * 250, (i + 1) * 250));
const results = await Promise.all(jobs);
console.log(results);
console.log("total:", results.reduce((a, b) => a + b, 0));
[ 31125, 93625, 156125, 218625 ]
total: 499500
- Verdict: stdlib. The language has no threads. Node.js gives
node:worker_threads, and browsers give Web Workers. - Each worker is an independent JavaScript thread with its own event loop. Workers exchange messages, which are copies. A
SharedArrayBufferlets them share memory. - A worker has no
join. The main thread waits for themessageevent, here wrapped in a promise.Promise.allkeeps the order of the jobs. - For waiting on I/O, use Async/await on one thread. Workers are for work that uses the CPU.
import { Worker } from "node:worker_threads";
interface Job {
start: number;
stop: number;
}
const source = `
const { parentPort, workerData } = require("node:worker_threads");
let sum = 0;
for (let n = workerData.start; n < workerData.stop; n++) sum += n;
parentPort.postMessage(sum);
`;
function partialSum(job: Job): Promise<number> {
return new Promise((resolve, reject) => {
const worker = new Worker(source, { eval: true, workerData: job });
worker.once("message", (sum: number) => resolve(sum));
worker.once("error", reject);
});
}
const jobs: Job[] = [0, 1, 2, 3].map((i) => ({ start: i * 250, stop: (i + 1) * 250 }));
const results: number[] = await Promise.all(jobs.map(partialSum));
console.log(results);
console.log("total:", results.reduce((a, b) => a + b, 0));
[ 31125, 93625, 156125, 218625 ]
total: 499500
- Verdict: stdlib. TypeScript has the threads of its runtime. In Node.js, these are the workers of
node:worker_threads. - The type checker does not see into the worker. The message that comes back has the type
any, so the code states its type, herenumber. - The worker code is a string of JavaScript, so it gets no type checking. A worker can also load its own file.
package main
import (
"fmt"
"sync"
)
func main() {
results := make([]int, 4)
var wg sync.WaitGroup
for i := range 4 {
wg.Add(1)
go func() {
defer wg.Done()
for n := i * 250; n < (i+1)*250; n++ {
results[i] += n
}
}()
}
wg.Wait()
fmt.Println(results)
var many sync.WaitGroup
count := make([]int, 10000)
for i := range count {
many.Add(1)
go func() {
defer many.Done()
count[i] = 1
}()
}
many.Wait()
total := 0
for _, c := range count {
total += c
}
fmt.Println("goroutines run:", total)
}
[31125 93625 156125 218625]
goroutines run: 10000
- Verdict: native. The
gostatement starts a goroutine. The runtime multiplexes goroutines onto a set of OS threads (M:N). - A goroutine has no handle and no
join. The result of the function is discarded.sync.WaitGroupwaits for a group, and each goroutine writes to its own slice element. - Starting 10,000 goroutines is a normal thing to do, because each one begins with a small stack that grows when needed.
- When
mainreturns, the program ends and does not wait for other goroutines (see Pitfalls).
use std::thread;
fn main() {
let handles: Vec<thread::JoinHandle<u64>> = (0..4u64)
.map(|i| thread::spawn(move || (i * 250..(i + 1) * 250).sum()))
.collect();
let results: Vec<u64> = handles.into_iter().map(|h| h.join().unwrap()).collect();
println!("{results:?}");
let data = vec![1u64, 2, 3, 4, 5, 6];
let (left, right) = data.split_at(3);
let (a, b) = thread::scope(|s| {
let a = s.spawn(|| left.iter().sum::<u64>());
let b = s.spawn(|| right.iter().sum::<u64>());
(a.join().unwrap(), b.join().unwrap())
});
println!("{a} + {b} = {}", a + b);
}
[31125, 93625, 156125, 218625]
6 + 15 = 21
- Verdict: stdlib.
std::thread::spawnstarts an OS thread and returns aJoinHandle<T>.join()returns the value of the closure, or anErrif the thread panicked. - A spawned thread can outlive the caller, so its closure must own its data (
move,'static). Dropping the handle detaches the thread. thread::scopejoins every thread it starts before it returns. Its threads may borrow local data, here two halves ofdata.
Without move, the closure borrows name, and the thread could outlive main. The compiler rejects the program with error E0373.
This code does not compile, on purpose.
use std::thread;
fn main() {
let name = String::from("worker");
let handle = thread::spawn(|| println!("{name}"));
handle.join().unwrap();
}
import kotlin.concurrent.thread
fun main() {
val results = LongArray(4)
val workers = (0 until 4).map { i ->
thread(name = "worker-$i") {
results[i] = (i * 250L until (i + 1) * 250L).sum()
}
}
workers.forEach { it.join() }
println(results.toList())
println("names: ${workers.map { it.name }}")
println("daemon: ${workers[0].isDaemon}")
val virtual = Thread.ofVirtual().start { results[0] = 0 }
virtual.join()
println("virtual: ${virtual.isVirtual}, first result now ${results[0]}")
}
[31125, 93625, 156125, 218625]
names: [worker-0, worker-1, worker-2, worker-3]
daemon: false
virtual: true, first result now 0
- Verdict: stdlib. Kotlin on the JVM uses
java.lang.Thread. The standard library functionkotlin.concurrent.threadmakes a thread and starts it by default. threadtakes the name, the daemon flag and the priority as named arguments, withisDaemon = falseby default.- Virtual threads come from the JDK, through
Thread.ofVirtual(), as in the Java example. - The library
kotlinx.coroutinesadds coroutines, which are not threads (see Async/await).
$results = 0..3 | ForEach-Object -ThrottleLimit 4 -Parallel {
$start = $_ * 250
$sum = 0
foreach ($n in $start..($start + 249)) {
$sum += $n
}
[pscustomobject]@{ Index = $_; Sum = $sum }
}
$sorted = $results | Sort-Object Index
$sorted | ForEach-Object { "thread $($_.Index): $($_.Sum)" }
"total: $(($sorted | Measure-Object Sum -Sum).Sum)"
$offset = 1000
$shifted = 1..3 | ForEach-Object -Parallel { $_ + $using:offset } | Sort-Object
$shifted -join ", "
thread 0: 31125
thread 1: 93625
thread 2: 156125
thread 3: 218625
total: 499500
1001, 1002, 1003
- Verdict: stdlib.
ForEach-Object -Parallelruns a script block for each input on a pool of threads in the same process.-ThrottleLimitsets the size of the pool, with 5 as the default. - Each script block runs in its own runspace, so it does not see the variables of the caller. The
$using:modifier passes a value in. - The output comes back in the order that the threads finish, so the program sorts it.
Variations and related ideas
- Processes. A process has its own address space, so its threads do not share memory with other processes. Python's
multiprocessingmodule andProcessPoolExecutoruse separate processes to run CPU-bound Python code in parallel in the default build.3 Bash runs background work as processes.26 - Thread pools. A pool keeps a set of threads and gives them tasks from a queue. It saves the cost of a fresh thread for each task. Python's
ThreadPoolExecutorusesmin(32, os.cpu_count() + 4)workers by default.15 C#Task.Runqueues work to the thread pool.13 Java virtual threads should not be pooled. JEP 444 recommends a semaphore to limit concurrency instead.19 - Scoped threads. A scope joins all of its threads before it returns, so no thread outlives the data that it uses. Rust's
thread::scopelets the threads borrow local variables, and a panic in a thread makes the scope panic.29 The destructor of a C++std::jthreadasks the thread to stop and then joins it.30 - Coroutines and async functions. An async function suspends without a thread of its own, and many of them share one thread. Async/await describes them. Java virtual threads keep the blocking thread-per-request style and still scale to large numbers of threads.19
- Workers with no shared memory. JavaScript workers exchange messages, and a
SharedArrayBufferlets them share memory.14 Message passing in this style is the subject of Channel. - Closures as thread bodies. Most languages start a thread with a closure. The closure captures the data of the thread, and the capture rules of Closure decide what the thread may touch. In Rust, a
moveclosure gives its data to the thread (see the Rust example).
Pitfalls
The program ends before the thread does
When main returns, a Go program exits at once, and the remaining goroutines stop.16 Here the goroutine needs 100 ms, and main does not wait for it.
This code runs but gives a wrong answer on purpose.
package main
import (
"fmt"
"time"
)
func main() {
go func() {
time.Sleep(100 * time.Millisecond)
fmt.Println("worker done")
}()
fmt.Println("main done")
}
main done
The fix is to wait. A sync.WaitGroup counts the goroutines, and Wait returns after each has called Done.
package main
import (
"fmt"
"sync"
"time"
)
func main() {
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
time.Sleep(100 * time.Millisecond)
fmt.Println("worker done")
}()
wg.Wait()
fmt.Println("main done")
}
worker done
main done
The same trap exists for daemon threads in Python and Java and for background threads in C#. These threads stop at the end of the program, in the middle of their work.31217 Join a thread that writes a file or sends a message.
A joinable std::thread is destroyed
If a std::thread is still joinable when its destructor runs, the destructor calls std::terminate.31 Here the function returns, and the thread object goes out of scope without join() or detach().
This code fails on purpose. The output below is the error.
#include <print>
#include <thread>
void start_worker() {
std::thread worker([] { std::println("working"); });
}
int main() {
start_worker();
std::println("after start_worker");
}
The C++ runtime aborts the program, and no line after the call runs. The fix is std::jthread, whose destructor joins the thread.30 A call of join() before the end of the scope also works.
#include <print>
#include <thread>
void start_worker() {
std::jthread worker([] { std::println("working"); });
}
int main() {
start_worker();
std::println("after start_worker");
}
working
after start_worker
An exception in a thread does not reach the caller
In Python, an exception that escapes the function of a Thread goes to threading.excepthook. The default hook prints it on sys.stderr.3 The caller of join() sees no error, and the result of that thread is missing.
This code runs but gives a wrong answer on purpose.
import threading
results = {}
def parse(text):
results[text] = int(text)
threading.excepthook = lambda args: None
workers = [threading.Thread(target=parse, args=(t,)) for t in ["1", "x", "3"]]
for worker in workers:
worker.start()
for worker in workers:
worker.join()
print(sorted(results.values()))
[1, 3]
The program silences the hook here, so the effect is clear: the run ends normally with one value missing. With the default hook, the traceback goes to stderr, and the program still ends normally. The fix is a future. Future.result() raises the same exception in the thread that asks for the result.15
from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=3) as pool:
futures = [pool.submit(int, t) for t in ["1", "x", "3"]]
for future in futures:
try:
print(future.result())
except ValueError as error:
print("error:", error)
1
error: invalid literal for int() with base 10: 'x'
3
In Rust, join() returns an Err when the thread panicked.10
A join with a timeout does not stop the thread
A join with a timeout only stops the wait. The thread keeps running. In Python, join(timeout) always returns None, so the caller must call is_alive() to know whether the thread ended.3
This code runs but gives a wrong answer on purpose.
import threading
import time
worker = threading.Thread(target=time.sleep, args=(0.5,))
worker.start()
result = worker.join(timeout=0.05)
print("join returned:", result)
print("finished:", result is None)
worker.join()
join returned: None
finished: True
The code treats None as success, but the thread is still asleep. The fix is to ask the thread.
import threading
import time
worker = threading.Thread(target=time.sleep, args=(0.5,))
worker.start()
worker.join(timeout=0.05)
print("finished:", not worker.is_alive())
worker.join()
print("finished:", not worker.is_alive())
finished: False
finished: True
In C#, Join(TimeSpan) returns false when the time runs out (see the C# example).32 To stop a thread, the program must tell it to stop, for example with a flag or a threading.Event that the thread checks.
The thread uses data that can disappear
A spawned thread may outlive the thread that spawned it.10 Data on the stack of the spawning function can disappear while the spawned thread still uses it. Rust rejects such a program. Here the closure borrows numbers, and the compiler stops with error E0373.
This code does not compile, on purpose.
use std::thread;
fn main() {
let numbers = vec![1, 2, 3];
let handle = thread::spawn(|| numbers.iter().sum::<i32>());
println!("{}", handle.join().unwrap());
}
There are two fixes. A move closure gives the vector to the thread. A scoped thread may borrow it, because thread::scope joins the thread before numbers goes away.29
use std::thread;
fn main() {
let numbers = vec![1, 2, 3];
let total = thread::scope(|s| s.spawn(|| numbers.iter().sum::<i32>()).join().unwrap());
println!("{total} from {numbers:?}");
}
6 from [1, 2, 3]
In C, the same mistake compiles with no error. The argument of pthread_create is often a pointer to a local variable. That memory must live until the thread no longer uses it (see the C example).
Cost
- Stack memory. Each OS thread gets its own stack. On Windows, the default stack reserves 1 MB of address space, and the committed pages use no physical memory until the program touches them.4 On Linux with NPTL, the default stack size is the soft limit for the stack resource. If that limit is unlimited, the size is 2 MB on most architectures.9 The Rust documentation gives 2 MiB as the default for spawned threads, and
Builder::stack_sizechanges it.10 A goroutine starts with a stack of a few kilobytes, which grows and shrinks as needed.20 - Creation and count. OS threads are costly, so a program cannot have very many of them. JEP 444 calls platform threads heavyweight and expensive. It says that a program that tries to make 10,000 platform threads at once might crash, depending on the machine and the OS.19 The Java example runs 10,000 virtual threads that each sleep, and the JDK runs them on a small number of carriers.
- Blocking. A blocked platform thread holds its OS thread. A blocked virtual thread unmounts and frees its carrier, unless it is pinned.19 For many tasks that wait on I/O, virtual threads, goroutines or async functions use fewer OS threads.
- Virtual threads are not faster. A virtual thread runs code at the same speed as a platform thread. Virtual threads give scale (more threads), not speed.19
- The GIL. In the default build of CPython, CPU-bound threads do not run Python code in parallel.3 The free-threaded build removes this limit, but single-threaded code runs slower. On the pyperformance suite, the average overhead is about 1% on macOS on ARM64 and 8% on x86-64 Linux.24
- Pools. A pool pays the cost of creation once for each worker, not once for each task. A task that waits for the result of another task in the same pool can deadlock, for example when all workers wait.15 Deadlock describes the general case.
History
- 1966. Jerome Saltzer's thesis on traffic control in a multiplexed computer defined a process as a program in execution. A footnote gives "thread" as an alternative term, suggested by Victor Vyssotsky.1
- 1996. LinuxThreads, the first POSIX thread library for Linux, was written. It handled each user-level thread with one kernel thread.18
- 2005. Ulrich Drepper and Ingo Molnar revised their design paper of the Native POSIX Thread Library on 21 February 2005. The paper explains the 1:1 model of Linux threads.18
- 2009. Go became a public open source project on 10 November 2009.33 Its
gostatement starts a goroutine, an independent thread of control in the same address space.2 - 2014. Go 1.4, released on 10 December 2014, reduced the starting stack of a goroutine from 8192 bytes to 2048 bytes.3435
- 2023. JDK 21 reached general availability on 19 September 2023 with virtual threads (JEP 444).3619 PEP 703, by Sam Gross, proposed a build of CPython without the GIL.23
- 2025. JDK 24, generally available on 18 March 2025, stopped
synchronizedfrom pinning virtual threads in nearly all cases (JEP 491).3721 PEP 779, accepted on 16 June 2025, made the free-threaded build a supported build of Python 3.14.3839
References
- Jerome H. Saltzer, Traffic Control in a Multiplexed Computer System, MIT Project MAC Technical Report TR-30, 1966, Section One, The concept of process, page 20, footnote 1
- The Go Programming Language Specification, Go statements
- The Python Standard Library, threading, Python 3.14, the CPython implementation detail on the GIL; GIL and performance considerations; Thread objects (join, daemon); threading.excepthook
- Microsoft Learn, Win32 apps, Thread Stack Size, the first two paragraphs (reserved and committed memory, default size of 1 MB)
- ISO/IEC 9899 working draft N3220 (the C23 draft), 5.1.2.5 Multi-threaded executions and data races, paragraph 1; 6.10.10.4 Conditional feature macros (__STDC_NO_THREADS__); 7.28.1 Introduction to threads, paragraph 2
- POSIX.1-2024, pthread_create, DESCRIPTION; CHANGE HISTORY (first released in Issue 5)
- POSIX.1-2024, pthread_join, DESCRIPTION; RATIONALE
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.thread.member], paragraphs 3, 4 and 8
- Linux manual page, pthread_create(3), NOTES (joinable by default; default stack size under NPTL)
- The Rust Standard Library, Module std::thread, The threading model; Spawning a thread; Stack size
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [futures.async], paragraph 1
- Java SE 25 API, java.lang.Thread, Platform threads; Virtual threads; join()
- .NET API reference, Task.Run Method, the summary of the method
- Node.js documentation, Worker threads, the introduction; Class Worker
- The Python Standard Library, concurrent.futures, Python 3.14, ThreadPoolExecutor (default max_workers); Future.result
- The Go Programming Language Specification, Program execution
- .NET documentation, Foreground and background threads, the first two paragraphs
- Ulrich Drepper and Ingo Molnar, The Native POSIX Thread Library for Linux, revision of 21 February 2005, The First Implementation; 1-on-1 vs. M-on-N
- JEP 444: Virtual Threads, Motivation; Description (virtual and platform threads, M:N scheduling); Do not pool virtual threads; Scheduling virtual threads; Pinning
- Go FAQ, Why goroutines instead of threads?
- JEP 491: Synchronize Virtual Threads without Pinning, Summary
- Python glossary, Python 3.14, global interpreter lock; free threading; free-threaded build
- PEP 703: Making the Global Interpreter Lock Optional in CPython, Abstract; Reference counting (biased, immortalization, deferred); Python critical sections; mimalloc
- Python HOWTOs, Python support for free threading, Python 3.14, Identifying free-threaded Python; The global interpreter lock in free-threaded Python; Single-threaded performance
- The Python Standard Library, sys, Python 3.14, sys._is_gil_enabled
- POSIX.1-2024, Shell Command Language, 2.9.3.1 Asynchronous AND-OR Lists
- PowerShell documentation, ForEach-Object, Description (Parallel running script block); Notes (runspace pool size, separate process threads)
- Kotlin standard library, kotlin.concurrent.thread, the signature and the parameters
- The Rust Standard Library, Function std::thread::scope, the description and the section on panics
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.jthread.cons], paragraph 11
- Working Draft, Programming Languages, C++ (N4950, the C++23 draft), [thread.thread.destr], paragraph 1
- .NET API reference, Thread.Join Method, Join(), Join(TimeSpan) and their return values
- Go FAQ, What is the history of the project?
- Go 1.4 Release Notes, Changes to the runtime
- Go release history, go1.4
- OpenJDK, JDK 21, the first paragraph and the schedule
- OpenJDK, JDK 24, the first paragraph
- PEP 779: Criteria for supported status for free-threaded Python, the header (Created, Resolution); Abstract
- What's new in Python 3.14, Free-threaded Python is officially supported
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 GTTVPE Edit this page History Report an error Markdown