skip to content

In C++, what happens when a std::thread object is destroyed while still joinable, and how do join() and detach() prevent it?

level: juniorimportance: must knowfreq 80%

answer

  1. the destructor checks one condition
  2. joinable means it still owns a thread
  3. std::terminate, not an exception
  4. join waits, detach lets go

basics

~20 s

The std::thread destructor calls std::terminate if the object is still joinable. Before it is destroyed, call join() to wait for the thread to finish or detach() to let it run on independently; both leave the object non-joinable.

solid answer

~40 s

A `std::thread` is *joinable* while it still represents a thread of execution, that is while `get_id() != std::thread::id()`. Its destructor, and its move assignment, call `std::terminate` if the object is joinable. The standard deliberately refused both alternatives: an implicit join can hide a long or endless wait, and an implicit detach lets a thread outlive the locals it uses. So every path out of the scope, exceptions included, must first call `join()`, which blocks until the thread finishes and makes its writes visible to the joiner, or `detach()`, which gives up the handle and lets the thread run unsupervised. A thread whose function has already returned is still joinable until one of the two is called. Calling either on a non-joinable object throws `std::system_error`. C++20's `std::jthread` joins in its destructor instead.

code

cpp · 12 lines
cpp
#include <iostream>
#include <thread>

void encode_segment(int id) {
    std::cout << "encoding segment " << id << '\n';
}

int main() {
    std::thread worker(encode_segment, 7);
    // Forgot worker.join() or worker.detach():
    // ~thread() sees joinable() == true and calls std::terminate.
}

go deeper

for a junior

Recall the one rule: a std::thread must be joined or detached before it is destroyed, or the program calls std::terminate.

for a middle

Explain joinable in terms of get_id, why a finished thread is still joinable, and what join synchronizes that detach does not.

for a senior

Show how every exit path joins, including exceptions after some workers have started, and why a join in a destructor can deadlock during unwinding.

for a principal

Argue for a team rule such as no raw detach and jthread or an owning guard by default, and what that costs in shutdown latency.

## What "joinable" means A `std::thread` object is a **handle**: it can represent one running (or finished but not yet collected) thread of execution, or nothing at all. The member `joinable()` is defined by the standard as `get_id() != id()`, so: - a default-constructed `std::thread` is **not** joinable; - a `std::thread` constructed with a function **is** joinable; - it stays joinable **after the function returns**, until `join()` or `detach()` is called; - a moved-from `std::thread` is not joinable, because the handle moved to the target. The third point catches people out. Finishing the work does not release the handle; only `join()` or `detach()` does. ## Why the destructor terminates The standard's wording for `~thread()` is short: if `joinable()`, invoke `std::terminate`; otherwise, no effect. Move assignment into a joinable `std::thread` does the same. A note in the standard explains the choice: implicitly **detaching** causes hard-to-debug correctness bugs, and implicitly **joining** causes performance bugs, both of which tend to surface only when an exception is thrown. Rather than pick one, the library forces you to decide. For a video transcoder that starts one worker per segment, the danger looks like this: a worker is started, then the next line throws (a bad segment header, a `std::bad_alloc`). Stack unwinding destroys the `std::thread`, it is still joinable, and the whole process ends in `std::terminate`, typically as an abort reported far from the line that caused it. ## join() versus detach() | | `join()` | `detach()` | |---|---|---| | Calling thread | blocks until the thread finishes | returns at once | | Afterwards `joinable()` | `false` | `false` | | Visibility | the thread's completion **synchronizes with** the return from `join()`, so its writes are visible | no synchronization; you need your own | | Who must keep data alive | the scope that joins | everything the thread touches, for as long as it might run | | Error | `std::system_error` if not joinable, or if a thread joins itself | `std::system_error` if not joinable | `join()` is the right default. `detach()` is for work whose lifetime genuinely does not matter to anyone, and it moves the burden of proving every captured object outlives the thread onto you. A detached thread that is still running when `main` returns keeps touching objects while static destructors run, and on mainstream platforms it is then cut off without its own destructors running. ## Moving ownership `std::thread` is **move-only**: copying is deleted, because two handles to one thread would make the join-or-detach rule meaningless. Moving transfers the handle and leaves the source non-joinable, which is how a function can start a worker and return it, and how `workers.emplace_back(encode_segment, id)` builds a vector of threads without copies. The one trap is the target: move-assigning into a `std::thread` that is still joinable calls `std::terminate`, just as destroying it would. Join or detach the old thread before reusing the variable. ## Making every path join 1. Keep the threads in a container and join them all in one place, as the example below does. 2. Wrap the handle in an RAII guard whose destructor joins if `joinable()`. 3. From C++20, use `std::jthread`, whose destructor requests a stop and then joins. The guard must not swallow the problem: joining in a destructor during unwinding can block if the worker is itself waiting on the code that is unwinding. That is exactly the deadlock the standard's note warns about, and why `std::jthread` pairs its join with a stop request. ## Sizing the worker count Transcoders often start `std::thread::hardware_concurrency()` workers. The standard says it returns the number of hardware thread contexts, that the value **should only be considered a hint**, and that if it is not computable or well-defined an implementation should return `0`. So write `std::max(1u, std::thread::hardware_concurrency())` and treat the number as an upper bound for CPU-bound work, not a promise. ## Common mistakes - Assuming the destructor joins, as `std::jthread` does; `std::thread` does not. - Believing a finished thread is no longer joinable. - Calling `join()` twice; the second call throws because the object is no longer joinable. - Detaching a thread that captured locals by reference, then returning from the function. - Catching an exception around thread creation but not joining the threads already started. The rule to say out loud: **every `std::thread` reaches its destructor non-joinable**, and the code shows how.

  • Why does std::thread not simply join in its destructor?
    The standard's own note says an implicit join causes performance bugs and an implicit detach causes correctness bugs, both mostly on exception paths. A join hidden in a destructor can block forever during unwinding if the worker waits on something the unwinding code would have provided. Terminating forces the author to choose. C++20's `std::jthread` does join, but it first calls `request_stop()` so a cooperative worker can finish.
  • What exactly does std::thread::hardware_concurrency() promise?
    It returns the number of hardware thread contexts, and the standard calls that value only a hint. If the number is not computable or well-defined, an implementation should return `0`, so code must guard with something like `std::max(1u, n)`. It says nothing about how many cores are free, cgroup or affinity limits, or the right pool size for I/O-bound work.
  • What can go wrong when a detached thread is still running at program exit?
    Returning from `main` calls `std::exit`, which destroys objects with static storage duration while the detached thread may still be using them, a race with undefined behaviour. The process then ends and, on mainstream platforms, the detached thread is cut off without unwinding, so its own destructors never run and buffered work is lost.

  • The std::thread destructor joins the thread automatically.
  • Destroying a joinable std::thread throws an exception the caller can catch.
  • Once the thread function returns, the std::thread object is no longer joinable.
  • detach() stops the thread or waits for it to finish.
  • hardware_concurrency() always returns the exact number of cores.