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
