Programming Search⌘K

Conceptcore

Join and detach

Also called thread join, join a thread, detach a thread, detached thread, joinable thread, zombie thread, daemon thread, background thread, pthread_join, pthread_detach, jthread.

To join a thread is to wait until it ends and take its result. To detach it is to let it run on its own. A program should do one of the two for each thread that it starts.

Applies to
core-languages

Idea

A program that starts a thread must decide what happens when the thread ends. There are two choices. To join a thread is to wait until it ends. The caller then knows that the work of the thread is complete, and it can take the result. To detach a thread is to give up the right to wait for it. The thread runs on its own, and the system frees its storage when it ends. POSIX says that one of the two "should eventually be called for every thread that is created so that storage associated with the thread may be reclaimed".1

Some runtimes add a third choice that is close to detach: a daemon thread, or background thread, does not keep the program alive. In Python, "the entire Python program exits when only daemon threads are left".2 The example below starts a child Python program twice. In each child, the main thread starts a worker that sleeps for 0.2 seconds and then prints a line. The main thread does not join the worker.

import subprocess
import sys

CHILD = """
import threading
import time


def work():
    time.sleep(0.2)
    print("worker finished", flush=True)


threading.Thread(target=work, daemon=DAEMON).start()
print("main returns", flush=True)
"""

for daemon in (False, True):
    code = CHILD.replace("DAEMON", str(daemon))
    result = subprocess.run([sys.executable, "-c", code], capture_output=True, text=True, check=True)
    print(f"daemon={daemon}:", result.stdout.splitlines())
Output
daemon=False: ['main returns', 'worker finished']
daemon=True: ['main returns']

With daemon=False, Python waits for the worker before the program exits, so the worker prints its line. With daemon=True, the program exits when the main thread returns, and the worker is stopped before it prints. In both cases the main thread does not know when the worker ends. Only a join gives that knowledge.

How it works

Joinable, detached and zombie threads

POSIX gives a name to each state. A new thread is joinable, unless it was created detached. It stays joinable until a call to pthread_join or pthread_detach for it succeeds.3 The two calls do different things:

  • pthread_join makes the caller wait: it "shall suspend execution of the calling thread until the target thread terminates, unless the target thread has already terminated". The value that the thread gives to pthread_exit becomes available to the caller.4
  • pthread_detach changes the thread "from joinable to detached", which tells the system that the storage of the thread "can be reclaimed when the thread terminates". The call does not stop the thread.1

A joinable thread that has ended, but that nobody has joined or detached, is a zombie thread. POSIX defines it as the remains of a joinable thread "after it terminates" and "before it has been joined".3 A zombie holds storage until a join or a detach frees it.

                      join returns
  joinable (running) -------------------------------> gone
       |          \
       | detach    \ thread ends
       v            v
  detached       zombie --- join or detach ---> gone
       |
       | thread ends
       v
     gone

What a join gives

A join is a point of synchronization. When it returns, the thread has ended, and its writes to memory are visible to the caller. The C++ reference says that the end of the thread synchronizes with the return from join.5 So the caller can read the results that the thread wrote without a lock. Most languages also give a way to return a value through the join. In Rust, the join handle gives the return value of the closure, and "If the spawned thread panics, join will return an Err".6

A join can also have a time limit. Python's join takes a timeout, but it always returns None, so "you must call is_alive" after it "to decide whether a timeout happened".2 Java's join(Duration) returns a boolean instead.7

What a detach gives up

After a detach, the program cannot wait for the thread, cannot take its result and cannot see its errors. A detached thread also does not keep the program alive. In Go, every goroutine is like a detached thread: when the main function returns, "the program exits", and the other goroutines do not finish first.8 In Rust, "When the main thread of a Rust program terminates, the entire program shuts down, even if other threads are still running".9

Daemon and background threads

Java, Python and .NET decide at the start of a thread whether the runtime waits for it at exit:

  • Java. "The shutdown sequence begins when all started non-daemon threads have terminated."7
  • Python. A daemon thread does not keep the program alive, and "Daemon threads are abruptly stopped at shutdown".2
  • .NET. A background thread is like a foreground thread with one exception: "a background thread does not keep the managed execution environment running".10

A daemon thread is still joinable in these languages. The flag only changes what happens at exit.

Handles that must be joined

In C++ and Rust, a thread object owns the thread, and the language decides what happens when the object goes away:

  • std::thread. If the object still has a thread when it is destroyed, the destructor calls std::terminate. After join or detach, the object has no thread and is safe to destroy.11 After detach, the object "no longer owns any thread".12
  • std::jthread. It "automatically rejoins on destruction". It also holds a stop source, and its destructor asks the thread to stop before it joins.13
  • Rust JoinHandle. If the handle is dropped, "the spawned thread will implicitly be detached".6 Inside thread::scope, the threads can borrow local data, because "the scope guarantees all threads will be joined at the end of the scope".14

In languages

LanguageVerdictNote
PythonStandard library
C++Standard library
JavaStandard library
CStandard libraryPthread_join and pthread_detach in POSIX, and thrd_join and thrd_detach in C11; no separate example file.
C#Standard library
JavaScriptStandard library
TypeScriptStandard libraryTypeScript on Node.js uses the Worker class of node:worker_threads, with the exit event and unref, as in the JavaScript example. No example file exists.
GoIdiom
RustStandard library
KotlinStandard libraryOn the JVM, Kotlin uses Thread.join and daemon threads, as in the Java example; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLDoes not applyA query does not start threads, so it has nothing to join or detach.
BashNativeThe wait builtin waits for background jobs and gives their exit status. No example file exists.
PowerShellStandard libraryWait-Job waits for background jobs and Receive-Job gets their output; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyMarkup has no threads.
CSSDoes not applyStyle rules have no threads.
Regular expressionsDoes not applyA pattern has no threads.

The example files join one thread and leave another thread running at the end of the program. They show the result of the join and the way each language lets the program exit without the second thread. The table gives the verdict for each tier 1 language.

Language Verdict Mechanism
Python stdlib Thread.join(timeout); daemon=True in place of detach
JavaScript stdlib Node.js Worker: the 'exit' event; unref()
TypeScript stdlib as JavaScript
Java stdlib Thread.join, join(Duration); daemon threads
Kotlin stdlib the Java Thread methods on the JVM
C# stdlib Thread.Join, Join(int); IsBackground
Go idiom no thread handle; wait with a channel or a sync.WaitGroup
Rust stdlib JoinHandle::join; drop the handle to detach; thread::scope
C stdlib pthread_join, pthread_detach; C11 thrd_join, thrd_detach
C++ stdlib std::thread::join, detach; std::jthread
Bash native wait for background jobs
PowerShell stdlib Wait-Job and Receive-Job for background jobs
SQL n/a a query does not start threads
Regex n/a a pattern has no threads
HTML/CSS n/a markup and style rules have no threads
  • C. POSIX has pthread_join and pthread_detach, and the C11 thread functions thrd_join and thrd_detach follow the same rules.3
  • Go. The go statement gives no handle, so a program cannot join a goroutine directly. The goroutine signals its end itself, through a channel or a sync.WaitGroup. See Wait for threads to finish.
  • JavaScript. A Node.js worker keeps the process alive while it runs. Calling unref() "allows the thread to exit if this is the only active handle in the event system".15
  • Rust. JoinHandle::is_finished tells whether the thread has ended, and "This function does not block".16 It lets a program join only a thread that has already ended.
PythonGitHub
import threading

release = threading.Event()
results = []


def work():
    release.wait()
    results.append("done")


worker = threading.Thread(target=work)
worker.start()
worker.join(timeout=0.05)
print("after join(timeout=0.05), alive:", worker.is_alive())
release.set()
worker.join()
print("after join(), alive:", worker.is_alive())
print("results:", results)
Output
after join(timeout=0.05), alive: True
after join(), alive: False
results: ['done']
  • Verdict: stdlib. Thread.join waits for the thread, with an optional timeout. Python has no detach; a daemon thread is the nearest choice, as the Idea section shows.
  • join returns None in both cases, so the example calls is_alive() to see whether the first join timed out.
  • The worker waits for an Event. The main thread sets the event and then joins, so the second join returns after the worker has added its result.
  • A join on a thread that has not started, or on the current thread, raises RuntimeError.
#include <chrono>
#include <iostream>
#include <stop_token>
#include <thread>

int main() {
    int answer = 0;
    std::thread worker([&answer] { answer = 6 * 7; });
    worker.join();
    std::cout << std::boolalpha;
    std::cout << "joined: answer = " << answer << ", joinable() = " << worker.joinable() << '\n';

    std::thread sleeper([] { std::this_thread::sleep_for(std::chrono::hours(1)); });
    sleeper.detach();
    std::cout << "detached: joinable() = " << sleeper.joinable() << '\n';

    {
        std::jthread poller([](std::stop_token token) {
            while (!token.stop_requested()) {
                std::this_thread::sleep_for(std::chrono::milliseconds(1));
            }
            std::cout << "jthread saw the stop request\n";
        });
    }  // The destructor of poller requests a stop, then joins.
    std::cout << "main returns; the detached thread ends with the process\n";
}
Output
joined: answer = 42, joinable() = false
detached: joinable() = false
jthread saw the stop request
main returns; the detached thread ends with the process
  • Verdict: stdlib. std::thread has join and detach, and std::jthread (C++20) joins in its destructor.
  • After join or detach, joinable() is false, and the object can be destroyed. If a joinable std::thread is destroyed, the program calls std::terminate.
  • join makes the write to answer visible to the main thread, so the main thread reads it without a lock.
  • The destructor of poller asks the thread to stop through its std::stop_token and then joins it. The thread checks the token and returns.
JavaGitHub
import java.time.Duration;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        Thread worker = Thread.ofPlatform().start(() -> System.out.println("worker ran"));
        worker.join();
        System.out.println("after join, alive: " + worker.isAlive());

        Thread sleeper = Thread.ofPlatform().daemon(true).start(() -> {
            try {
                Thread.sleep(Duration.ofHours(1));
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        });
        boolean ended = sleeper.join(Duration.ofMillis(50));
        System.out.println("daemon ended within 50 ms: " + ended);
        System.out.println("main returns; the JVM does not wait for the daemon thread");
    }
}
Output
worker ran
after join, alive: false
daemon ended within 50 ms: false
main returns; the JVM does not wait for the daemon thread
  • Verdict: stdlib. Thread.join() waits without a limit, and join(Duration) waits for a limited time and returns true if the thread has ended.
  • Java has no detach. A daemon thread does not delay the shutdown of the JVM, so it acts like a detached thread at exit. The flag must be set before the thread starts; here the builder sets it.
  • The sleeper thread is still running when main returns. The JVM exits because only a daemon thread is left.
  • Virtual threads are always daemon threads.
using System;
using System.Threading;

var worker = new Thread(() => Console.WriteLine("worker ran"));
worker.Start();
worker.Join();
Console.WriteLine($"after Join, alive: {worker.IsAlive}");

var sleeper = new Thread(() => Thread.Sleep(Timeout.Infinite)) { IsBackground = true };
sleeper.Start();
bool ended = sleeper.Join(50);
Console.WriteLine($"background thread ended within 50 ms: {ended}");
Console.WriteLine("main returns; the runtime does not wait for the background thread");
Output
worker ran
after Join, alive: False
background thread ended within 50 ms: False
main returns; the runtime does not wait for the background thread
  • Verdict: stdlib. Thread.Join() waits without a limit, and Join(int) waits for a number of milliseconds and returns true if the thread has ended.
  • .NET has no detach for a Thread. A background thread, with IsBackground = true, does not keep the process running, so it acts like a detached thread at exit.
  • The sleeper thread never ends by itself. The process exits when the top-level statements return, because only a background thread is left.
  • Threads from the thread pool are background threads. A Task is waited for with Wait or await, not with Join.
JavaScriptGitHub
import { Worker } from "node:worker_threads";

const source = `
const { parentPort } = require("node:worker_threads");
parentPort.postMessage(6 * 7);
`;

const worker = new Worker(source, { eval: true });
let answer;
worker.on("message", (value) => {
  answer = value;
});
worker.on("exit", (code) => {
  console.log(`worker exit code: ${code}, answer: ${answer}`);

  const forever = new Worker("setInterval(() => {}, 1000);", { eval: true });
  forever.unref();
  console.log("main returns; the unref'd worker does not keep Node.js alive");
});
Output
worker exit code: 0, answer: 42
main returns; the unref'd worker does not keep Node.js alive
  • Verdict: stdlib. A Node.js Worker has no blocking join. The 'exit' event plays the part of a join: it fires after the worker has stopped, with its exit code.
  • The worker sends its result with postMessage, and the main thread keeps it until the 'exit' event.
  • The second worker runs a timer, so it never ends by itself. unref() lets the process exit while it runs, as a detach would.
  • worker.terminate() stops a worker from the main thread.
package main

import "fmt"

func main() {
	done := make(chan int)
	go func() {
		done <- 6 * 7
	}()
	fmt.Println("result through a channel:", <-done)

	block := make(chan struct{})
	go func() {
		<-block
		fmt.Println("never printed")
	}()
	fmt.Println("main returns; the blocked goroutine ends with the program")
}
Output
result through a channel: 42
main returns; the blocked goroutine ends with the program
  • Verdict: idiom. A go statement gives no handle, so Go has no join and no detach. The goroutine itself reports its end, here by a send on a channel.
  • The receive <-done waits until the first goroutine has sent its result, so it acts as a join that also carries a value.
  • The second goroutine waits on a channel that nobody closes. When main returns, the program exits and the goroutine ends with it.
  • To wait for many goroutines, use a sync.WaitGroup, as in Wait for threads to finish.
RustGitHub
use std::sync::mpsc;
use std::thread;

fn main() {
    let handle = thread::spawn(|| 6 * 7);
    let answer = handle.join().expect("the thread panicked");
    println!("joined: {answer}");

    std::panic::set_hook(Box::new(|_| {}));
    let failed = thread::spawn(|| -> i32 { panic!("bad input") });
    println!("join of a panicked thread is Err: {}", failed.join().is_err());
    let _ = std::panic::take_hook();

    let mut data = vec![1, 2, 3];
    thread::scope(|s| {
        s.spawn(|| data.push(4));
    });
    println!("after the scope: {data:?}");

    let (keep_open, never) = mpsc::channel::<()>();
    let waiting = thread::spawn(move || {
        let _ = never.recv();
    });
    println!("waiting thread finished: {}", waiting.is_finished());
    drop(waiting);
    println!("main returns; the dropped handle detached the thread");
    drop(keep_open);
}
Output
joined: 42
join of a panicked thread is Err: true
after the scope: [1, 2, 3, 4]
waiting thread finished: false
main returns; the dropped handle detached the thread
  • Verdict: stdlib. JoinHandle::join waits for the thread and returns its result, or an Err if the thread panicked. A dropped JoinHandle detaches the thread.
  • The example sets an empty panic hook so that the panic prints nothing, then restores the default hook with take_hook.
  • thread::scope joins every thread that it started before it returns. So the scoped thread can borrow data mutably, and the main thread reads it after the scope.
  • The waiting thread blocks on a channel whose sender stays open, so it is still running. is_finished does not block. After drop, nothing can join the thread, and the program does not wait for it when main returns.
  • Scoped threads. A scope joins all of its threads before it returns, so no thread can outlive the data that it borrows. Rust's thread::scope works this way.14 std::jthread gives the same result for one thread, because its destructor joins.13
  • Join with a timeout. The caller waits for a limited time and then does other work. The thread is still joinable after a timeout.
  • Ask, then join. A thread cannot be stopped safely from outside, so the caller sets a flag or an event that the thread checks, and then joins it. The stop token of std::jthread is one form of this.13 Python recommends that threads which must stop gracefully be non-daemonic and use "a suitable signalling mechanism such as an Event".2
  • Futures and promises. A future joins on a result, not on a thread. The thread can return to a pool and run other tasks.
  • Process exit codes. A parent process waits for a child process in the same way, and a child that has ended but has not been waited for is a zombie process.

Pitfalls

  • Neither join nor detach. The thread's storage stays allocated after it ends. In Rust, "It is the responsibility of the program to either eventually join threads it creates or detach them; otherwise, a resource leak will result."6 For a std::thread, the result is worse: the destructor of a joinable object calls std::terminate.11
  • A join on the wrong thread. In POSIX, a join on the calling thread itself is undefined, and so are several joins on the same thread at the same time.4 Python raises RuntimeError for a join on the current thread, "as that would cause a deadlock".2
  • A timeout that is not checked. After join(timeout) in Python, the thread can still be alive. Call is_alive() before the program uses the results of the thread.2
  • A detached thread that uses data that is gone. A detached thread can still run after the function that started it has returned. If it uses a local variable of that function, the variable no longer exists. Rust prevents this: thread::spawn takes only data that lives long enough, and thread::scope allows borrowed data only because it joins.14
  • Daemon threads that hold resources. A daemon thread can stop in the middle of its work. In Python, its resources "may not be released properly".2 In .NET, the runtime stops a background thread at exit without an exception in the thread.10 Do not give a file write or a transaction to a daemon thread.

Cost

  • Storage. Each thread that has ended but has not been joined holds storage until the program joins or detaches it.1
  • Waiting. A join blocks the caller. A thread that joins workers one at a time cannot do other work in the meantime.
  • Detach. A detach costs almost nothing, but the program then needs another way to know that the work is done, for example a channel or an event.

History

The names come from POSIX threads. The functions pthread_join and pthread_detach first appeared in Issue 5 of the specification, "for alignment with the POSIX Threads Extension".4 C++11 added std::thread with join and detach.12 C++20 added std::jthread, which joins in its destructor and can ask its thread to stop.13 Rust's thread::scope, which joins all threads at the end of a scope, became stable in Rust 1.63.0.14

References

  1. POSIX.1-2024, pthread_detach, DESCRIPTION; RATIONALE
  2. Python documentation, threading, Thread objects, Thread objects; join
  3. POSIX.1-2024, Base Definitions, chapter 3, Definitions, 3.183 Joinable Thread; 3.427 Zombie Thread
  4. POSIX.1-2024, pthread_join, DESCRIPTION; CHANGE HISTORY
  5. std::thread::join, cppreference.com, the description
  6. The Rust Standard Library, function std::thread::spawn, the description of the join handle
  7. Java SE 21 API, java.lang.Thread, Platform threads; join(Duration); setDaemon
  8. The Go Programming Language Specification, Program execution
  9. The Rust Standard Library, module std::thread, The threading model
  10. Microsoft Learn, .NET, Foreground and background threads, the whole article
  11. std::thread::~thread, cppreference.com, the description; Notes
  12. std::thread::detach, cppreference.com, the description; Postconditions
  13. std::jthread, cppreference.com, the description
  14. The Rust Standard Library, function std::thread::scope, the description
  15. Node.js documentation, Worker threads, worker.unref()
  16. The Rust Standard Library, struct std::thread::JoinHandle, is_finished

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