Detaching threads
What you'll learn: How to let threads clean up after themselves automatically so you don't have to wait for them.
The "Fire and Forget" Approach
By default, when you create a thread in C using pthread_create, it is joinable. This means the system keeps the thread's exit status and resources around after it finishes, waiting for the main program to call pthread_join. Think of this like a restaurant where the waiter keeps your receipt at the table until you personally come back to sign it.
However, sometimes you don't care when a thread finishes or what it returns. You might have a background task—like an autosave feature or a logging service—that should just run until it's done and then disappear. In these cases, you "detach" the thread.
How to Detach
A detached thread is independent. Once it finishes, the operating system immediately reclaims its resources (like its stack and internal state) without needing you to call pthread_join.
You can detach a thread using pthread_detach(thread_id). Once a thread is detached, it cannot be joined again, and you cannot retrieve its return value. It truly becomes a "fire and forget" task.
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void* background_task(void* arg) {
printf("Background log: Saving data...\n");
sleep(2);
printf("Background log: Save complete.\n");
return NULL;
}
int main() {
pthread_t thread;
pthread_create(&thread, NULL, background_task, NULL);
// We don't want to wait, so we detach it immediately
pthread_detach(thread);
printf("Main thread is moving on to other work...\n");
sleep(3); // Wait long enough for the detached thread to finish
return 0;
}
Why Detach?
The main reason to use pthread_detach is to prevent resource leaks. Every thread you create uses memory. If you don't join a joinable thread, that memory stays "zombified" even after the thread stops running. If your program creates thousands of short-lived threads without joining or detaching them, it will eventually run out of memory.
Detaching is the cleanest way to handle threads that perform background work where the timing of their completion doesn't impact the rest of your program's logic.
Key takeaway
Detaching a thread tells the system to automatically recycle the thread's memory as soon as it finishes, removing the need to call pthread_join.