Linux System Programming · beginner · ~10 min

pthread_create() and pthread_join()

Spawn a thread and wait for it to finish.

Lesson

pthread_create(pthread_t *t, attr, fn, arg) starts a new thread that runs fn(arg). It returns immediately — the new thread runs concurrently with the caller.

pthread_join(t, &retval) blocks until thread t finishes, then puts its return value (the pointer it returned) in *retval. Every thread you create must either be joined or detached (pthread_detach), otherwise its resources leak until the process exits.

pthread_create returns 0 on success, or an errno on failure. (Unlike most syscalls, it does NOT set the global errno — check the return value.)

Code examples

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>

static void *worker(void *arg) {
    int *n = arg;
    printf("worker got %d\n", *n);
    return NULL;
}

int main(void) {
    int x = 42;
    pthread_t t;
    int rc = pthread_create(&t, NULL, worker, &x);
    if (rc != 0) { fprintf(stderr, "create: %s\n", strerror(rc)); return 1; }
    pthread_join(t, NULL);
    return 0;
}

Line by line

pthread_t t;                              // opaque handle
pthread_create(&t, NULL, worker, &x);     // spawn; worker runs concurrently
pthread_join(t, NULL);                    // wait for it; pass &retval to receive

Common mistakes

  • Forgetting pthread_join and letting main return — the thread is killed mid-execution.
  • Checking errno after pthread_create. It doesn't set errno; check the return value.

Summary

pthread_create starts a thread; pthread_join waits for it. Always join or detach to avoid leaks. Return value of pthread_create is an errno, not -1.

Practice with these exercises