A structured lesson workspace with readable content, hands-on examples, and a clean path to completion.
A joinable thread retains its resources (stack, thread ID, exit status) until another thread calls pthread_join. A detached thread releases its resources automatically when it exits. No join is needed. No join is possible. Detached threads are for fire-and-forget tasks: background logging, periodic cleanup, asynchronous notifications. You launch them and do not track their completion.
#include <stdio.h>#include <pthread.h>#include <unistd.h>void *background_task(void *arg) {const char *name = (const char *)arg;printf("%s: running\n", name);sleep(1);printf("%s: finished\n", name);return NULL;}int main(void) {pthread_t t1, t2;pthread_attr_t attr;pthread_attr_init(&attr);pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);pthread_create(&t1, &attr, background_task, "Logger");pthread_create(&t2, &attr, background_task, "Monitor");pthread_attr_destroy(&attr);printf("Main: threads launched, sleeping...\n");sleep(3);printf("Main: exiting\n");return 0;}
The threads are created detached via the attribute. No pthread_join is called. When each thread returns from its function, its resources are freed automatically. The main thread sleeps to give the background threads time to complete. In a real application, main would continue doing useful work rather than sleeping. If main exits before the detached threads finish, they are terminated.
You can also detach a joinable thread after creation: pthread_detach(t1). After this call, t1 cannot be joined. Its resources will be freed on exit. This is useful when you initially create a thread joinable but later decide you do not need to wait for it. The detach is irreversible.
Detached threads are the fire-and-forget pattern. Use them for background work whose completion you do not need to track. Use joinable threads when you need to wait for results or synchronize shutdown. The choice is about whether the caller cares when the thread finishes. Next: memory leaks, the slow death of a long-running C program.
Finish the lesson once you have worked through the material. This awards ★ 30 XP.