liveBook · Manning

Std::thread::detach()

As explained in C++ Concurrency in Action, Second Edition

`std::thread::detach()` separates a thread of execution from its `std::thread` object, allowing it to continue independently.

Calling detach() leaves a thread running independently of its std::thread object. The object is no longer associated with the thread, cannot be used to join it, and is no longer joinable. The C++ runtime reclaims the thread’s resources when it exits. section 2.1.4

Detach only when the object has an associated thread, which joinable() can check. Detached work has no direct communication or joining mechanism through that object. Ensure anything the worker accesses remains valid until it finishes: detaching a worker that holds a reference to a local variable can leave it using that variable after it is destroyed, causing undefined behavior. section 2.1.1 section 2.1.4

Detached threads are used for background work such as:

  • Long-running tasks, such as filesystem monitoring, cache cleanup, or data-structure optimization. section 2.1.4
  • Fire-and-forget tasks, or work whose completion is identified through another mechanism. section 2.1.4
std::thread t(do_background_work);
t.detach();
assert(!t.joinable());

After detach(), the thread object is no longer joinable. section 2.1.4

Listing 2.4. Detaching a thread to handle other documents
void edit_document(std::string const& filename)
{
    open_document_and_display_gui(filename);
    while(!done_editing())
    {
        user_command cmd=get_user_input();
        if(cmd.type==open_new_document)
        {
            std::string const new_name=get_filename_from_user();
            std::thread t(edit_document,new_name);
            t.detach();
        }
        else
        {
            process_user_input(cmd);
        }
    }
}

Opening another document launches a separate editing task and detaches it, allowing the current editing loop to continue. section 2.1.4

How C++ Concurrency in Action, Second Edition covers it

How deep it goes
Explains detachment effects and preconditions, then traces how a detached worker can outlive referenced local data.
Examples
Uses background maintenance tasks, a dangling-reference worker, and detached document-editing threads.
What it assumes
Assumes a launched std::thread and explains the associated-thread requirement for calling detach().
What you can do after
Operate std::thread by detaching only joinable threads and keeping worker-accessed data alive until the work finishes.
How it connects
Connects detachment to std::thread, join(), joinable(), and object and data lifetimes.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of C++ Concurrency in Action, Second Edition. The section links point to the parts of the book it draws on.