typestar

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

  1. pthread_detach releases the resources on exit.
  2. There is no way to collect its return value.
  3. The main thread must not exit while it still matters.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Starting threads, step 3 of 10 in Threads & concurrency.

← Previous Next →