Linux System Programming · beginner · ~10 min

pthread_create() and pthread_join()

Start a new thread, then wait for it to finish before your program continues.

Lesson

Starting a thread

A thread is a separate flow of execution inside the same process. Use pthread_create to start one:

pthread_create(pthread_t *t, attr, fn, arg);

It launches a new thread that runs fn(arg). The call returns right away. The new thread then runs concurrently with the caller, so both can make progress at the same time.

Waiting for a thread

Use pthread_join to wait for a thread to complete:

pthread_join(t, &retval);

This call blocks (pauses the caller) until thread t finishes. When the thread is done, its return value (the pointer it returned) is stored in *retval.

Every thread you create must be handled in one of two ways:

  • Join it with pthread_join, or
  • Detach it with pthread_detach.

If you do neither, the thread's resources leak until the process exits.

Checking for errors

pthread_create returns 0 on success, or an error number (an errno value) on failure.

This is different from most system calls. It does not set the global errno variable. Always check the return value directly.

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

  • Letting main return without joining. If main finishes while a thread is still running, the thread is killed mid-execution. Call pthread_join (or detach the thread) first.
  • Checking errno after pthread_create. This function does not set errno. Check its return value instead.

Summary

  • pthread_create starts a new thread that runs concurrently with the caller.
  • pthread_join blocks until a thread finishes and gives you its return value.
  • Always join or detach every thread, or its resources leak.
  • pthread_create returns an errno value on failure, not -1, and does not set errno.

Practice with these exercises