Linux System Programming · beginner · ~10 min
Start a new thread, then wait for it to finish before your program continues.
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.
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:
pthread_join, orpthread_detach.If you do neither, the thread's resources leak until the process exits.
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.
#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;
}
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
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.errno after pthread_create. This function does not set errno. Check its return value instead.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.pthread_create returns an errno value on failure, not -1, and does not set errno.