CSE Roadmap

Core tier · about 4 hours · 6 parts

Part 4 of 6 · 2 min read

Join or detach

In plain words: When a thread ends, the system keeps a small record of it, with its return value, until somebody collects it. This is the thread version of the zombie (Level 1, page 8). A joinable thread, which is the default, keeps that record until pthread_join is called on it. If the program never joins, the records pile up.

When the result does not matter and nobody wants to wait, a thread can be made detached. A detached thread cleans up after itself when it ends, and it cannot be joined. A thread is made detached either at creation, with an attribute, or later with pthread_detach:

#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
static void *bg(void *a) { (void)a; usleep(100000); printf("detached thread finished\n"); return NULL; }
int main(void) {
    pthread_t t; pthread_attr_t at;
    pthread_attr_init(&at);
    pthread_attr_setdetachstate(&at, PTHREAD_CREATE_DETACHED);
    pthread_create(&t, &at, bg, NULL);
    pthread_attr_destroy(&at);
    printf("main waits 0.3 s\n");
    usleep(300000);
    return 0;
}
main waits 0.3 s
detached thread finished

The thread ran to the end on its own while main waited. Without that 0.3-second sleep, main would have returned first and the whole process would have ended before the thread printed (next section).

The choice is simple. If another thread needs the result or must know that the work is done, keep the thread joinable and join it. If the thread is a background job, such as a handler for one client request, make it detached.

Joinable and detached thread

A joinable thread keeps its exit status until another thread calls pthread_join for it. A detached thread releases its resources automatically when it ends, and no thread can join it.

Example: a worker whose answer is needed is joinable; a thread that logs a message and ends is detached.

Check yourself: 1. What happens to the record of a joinable thread that nobody joins? 2. Can you join a detached thread? 3. Which kind suits a handler for one client request?