Introduction
In C++, after starting a thread with std::thread, you typically need to wait for it to finish using .join(). However, there are times when you want to “start it and leave it to finish in the background” without the main thread waiting.
The .detach() method allows you to “abandon monitoring and let it run independently in the background.” When called, the connection between the thread object and the actual thread managed by the OS is severed.
In this article, I will explain the basic usage of .detach() and the very important precautions when using it.
Sample Code Using detach()
This code starts a worker thread background_task and immediately detaches it. The main thread continues its own processing without waiting for the worker thread, and the worker thread operates autonomously in the background.
#include <iostream>
#include <thread>
#include <chrono>
using namespace std;
// Task to be executed in the background
void background_task() {
cout << "Background Task: Started (takes 3 seconds)..." << endl;
this_thread::sleep_for(chrono::seconds(3));
cout << "Background Task: Completed." << endl;
}
int main() {
cout << "Main Thread: Starting background task." << endl;
// 1. Start the thread
thread worker(background_task);
// 2. Detach the thread
worker.detach();
cout << "Main Thread: Detached worker thread. Proceeding without waiting with .join()." << endl;
// Main thread performs other processing
this_thread::sleep_for(chrono::seconds(1));
cout << "Main Thread: Executing other processing..." << endl;
// 3. Wait long enough to prevent main from exiting before the detached thread finishes
this_thread::sleep_for(chrono::seconds(3));
cout << "Main Thread: Exiting." << endl;
return 0;
}
Code Explanation
worker.detach();
This single line is the command to detach the thread.
- After calling
detach(), thethreadobjectworkerbecomes an “empty” state and no longer manages any thread. - On the other hand, the actual thread running
background_taskcontinues its processing in the background under OS management. Such an independent thread is sometimes called a “daemon thread.” - You cannot call
.join()later on athreadobject that has calleddetach().
[Most Important] Cautions for detach()
No one waits for a thread that has used detach(). Therefore, if the main thread (main function) finishes first, the detached thread is forcibly terminated even if it is in the middle of processing.
The sleep_for at the end of the sample code is used to avoid this problem. Unless you implement your own synchronization mechanism (such as mutexes or condition variables) to ensure that the detached thread completes, using detach is very dangerous.
Should You Use join() or detach()?
You must call either .join() or .detach() before the thread object is destroyed (goes out of scope). If the thread object is destroyed without calling either, the program will force quit.
| Method | Purpose | Safety |
| .join() | Wait for the thread to finish | ◎ (Safe) |
| .detach() | Detach the thread (background execution) | △ (Dangerous) |
In conclusion, you should always use .join() unless there is a special reason. .detach() makes application lifetime management very complex and causes hard-to-debug bugs, so it should only be used by advanced users in limited situations where the behavior is fully understood.
Summary
In this article, I explained how to use std::thread::detach() to run threads independently in the background.
.detach()severs the relationship between thethreadobject and the actual thread.- The detached thread is forcibly terminated if the main program ends.
- From a safety perspective, using
.join()is strongly recommended in principle.
