Detached threads in C
A detached thread cleans up after itself, and can never be joined.
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
static void *background(void *arg) {
(void) arg;
printf("background work\n");
return NULL;
}
int fire_and_forget(void) {
pthread_t thread;
if (pthread_create(&thread, NULL, background, NULL) != 0) {
return 0;
}
if (pthread_detach(thread) != 0) {
return 0;
}
sleep(1);
return 1;
}
How it works
pthread_detachreleases the resources on exit.- There is no way to collect its return value.
- The main thread must not exit while it still matters.
Keywords and builtins used here
NULLbackgroundfire_and_forgetifintreturnstaticthreadvoid
The run, in numbers
- Lines
- 21
- Characters to type
- 341
- Tokens
- 91
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 55 seconds.
Step 3 of 3 in Starting threads, step 3 of 10 in Threads & concurrency.