Create and Join Threads with pthread_create
Start threads with pthread_create, wait for them with pthread_join and check the error codes correctly. Includes a complete C program and the mistakes to avoid.

The first thing every systems programmer does with threads is start one, and the first thing that goes wrong is that nothing happens, or the program exits before the thread finishes, or pthread_create fails and the code carries on as if it had worked. The POSIX threads API is small, but its error convention is different from the rest of the C library, and the lifecycle rules (every thread must be joined or detached) are easy to forget. This post builds the smallest correct program on Linux with glibc 2.41 and GCC 15, then grows it to several threads. If you are new to the distinction between a thread and a process, Processes vs Threads covers it first.
The two calls
pthread_create starts a thread. Its signature, from POSIX.1-2024, is:
int pthread_create(pthread_t *restrict thread,
const pthread_attr_t *restrict attr,
void *(*start_routine)(void *),
void *restrict arg);The first argument receives the new thread's handle. The second is an attribute object, and NULL means defaults. The third is the function the thread runs, which must take a void * and return a void *. The fourth is the single argument passed to that function. On success the call returns 0.
pthread_join waits for a thread to finish:
int pthread_join(pthread_t thread, void **retval);It blocks the caller until thread returns from its start routine (or calls pthread_exit), then stores the thread's return value in *retval if retval is not NULL. Joining also releases the thread's resources. A joinable thread that is never joined leaks them until the process exits.
The smallest complete program
#include <pthread.h>
#include <stdio.h>
static void *greet(void *arg)
{
const char *name = arg;
printf("hello from the worker, %s\n", name);
return NULL;
}
int main(void)
{
pthread_t worker;
int rc = pthread_create(&worker, NULL, greet, "Ada");
if (rc != 0) {
fprintf(stderr, "pthread_create failed: error %d\n", rc);
return 1;
}
rc = pthread_join(worker, NULL);
if (rc != 0) {
fprintf(stderr, "pthread_join failed: error %d\n", rc);
return 1;
}
printf("worker finished\n");
return 0;
}Build it with gcc -Wall -Wextra -pthread -o hello_thread hello_thread.c and run it:
hello from the worker, Ada
worker finishedThe order is guaranteed here, not by luck: main prints "worker finished" only after pthread_join returns, and the join cannot return until greet has returned. Without the join, main would return, the process would exit, and the worker could be killed before it printed anything.
Errors are return values, not errno
Most C library calls return -1 and set errno. The pthread functions do not. They return the error number directly and leave errno alone. That is why the code above stores rc and tests it, rather than checking errno after a -1.
The values you may meet from pthread_create are listed in pthread_create(3):
| Return | Meaning |
|---|---|
EAGAIN | The system lacks resources, or a limit such as RLIMIT_NPROC or the maximum thread count was reached |
EINVAL | The attribute object holds invalid settings |
EPERM | No permission to set the scheduling policy or parameters the attribute asked for |
To print a readable message, pass the code to strerror:
fprintf(stderr, "pthread_create: %s\n", strerror(rc));A helper keeps that tidy across a program:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define CHECK_PTHREAD(call) \
do { \
int rc_ = (call); \
if (rc_ != 0) { \
fprintf(stderr, "%s:%d: %s failed: %s\n", \
__FILE__, __LINE__, #call, strerror(rc_)); \
exit(EXIT_FAILURE); \
} \
} while (0)If you do call pthread_create with a thread count driven by user input and the limit is hit, the EAGAIN path really executes, so handle it the way you would handle a failed malloc.
Starting several threads
A real program starts a group of workers and joins them all. Keep the handles in an array, and give each thread its own slot to write its result into, so the threads share no variable:
#include <pthread.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define WORKERS 4
struct job {
int input;
long result;
};
static void *square(void *arg)
{
struct job *job = arg;
job->result = (long)job->input * job->input;
return NULL;
}
int main(void)
{
pthread_t threads[WORKERS];
struct job jobs[WORKERS];
for (int i = 0; i < WORKERS; i++) {
jobs[i].input = i + 2;
jobs[i].result = 0;
int rc = pthread_create(&threads[i], NULL, square, &jobs[i]);
if (rc != 0) {
fprintf(stderr, "pthread_create: %s\n", strerror(rc));
return EXIT_FAILURE;
}
}
for (int i = 0; i < WORKERS; i++) {
int rc = pthread_join(threads[i], NULL);
if (rc != 0) {
fprintf(stderr, "pthread_join: %s\n", strerror(rc));
return EXIT_FAILURE;
}
}
for (int i = 0; i < WORKERS; i++)
printf("%d squared is %ld\n", jobs[i].input, jobs[i].result);
return 0;
}2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25The threads run in whatever order the scheduler picks, but the output is stable because the printing happens in the main thread after every join. Two details matter. First, jobs lives in main's stack frame, which outlives the threads because main joins them before it returns. Passing the address of a local is safe only when that guarantee holds. Second, each thread writes only to jobs[i], so there is no shared mutable state to protect.
What the join gives you beyond waiting
Joining does three things: it blocks until the thread is done, it hands back the return value, and it frees the thread's bookkeeping. It also establishes ordering. Everything the thread wrote before returning is visible to the joiner after the join, which is why reading jobs[i].result afterwards needs no lock. POSIX specifies this synchronization in its memory visibility rules.
Joining has limits:
A thread can be joined only once. A second
pthread_joinon the same handle is undefined behavior; glibc typically reportsESRCHorEINVAL, but do not rely on it.A thread cannot join itself. Trying returns
EDEADLK.A detached thread cannot be joined at all. That is what pthread_detach is for.
Common mistakes
Passing the address of a loop variable is the classic one:
for (int i = 0; i < WORKERS; i++)
pthread_create(&threads[i], NULL, worker, &i); // wrongEvery thread receives the same pointer, and by the time a thread reads *arg the loop may have changed i. The fix is the array of job structs above, or heap-allocating one argument per thread and freeing it inside the thread.
Another is returning a pointer to a local variable from the start routine. The thread's stack is gone after the join, so the returned address dangles. Return a heap pointer, or write into a caller-owned struct as in the example.
A third is forgetting -pthread. On glibc 2.34 and later pthread_create lives in libc itself, so a missing flag often links anyway, but older systems fail with undefined reference to 'pthread_create'. Use the flag on both compile and link, as the linking post explains.
When pthreads are the wrong tool
If you are writing C++ or Rust, use std::thread or std::thread::spawn, which wrap the same primitives with safer ownership. If you need portability to Windows without a compatibility layer, C11 <threads.h> offers thrd_create and thrd_join, though glibc's implementation is a thin wrapper over the pthread one. If the work is many short tasks, start a pool once rather than creating a thread per task.
Testing a thread program
A threaded program that works once has proved little, because scheduling differs on every run. Three habits make the examples above trustworthy. First, run the program in a loop a few hundred times, since a missing join or a shared variable often fails only occasionally. Second, build once with -fsanitize=thread and run again: ThreadSanitizer reports a data race even on a run where the wrong answer did not appear. Third, force the error path. You can lower the thread limit for one shell with ulimit -u and check that your EAGAIN handling prints a message and exits cleanly, instead of crashing on an uninitialized handle.
Keep thread creation in one function that returns an error code to its caller. A program that calls pthread_create from ten places has ten places to forget the check, and one wrapper with a descriptive failure message is easier to test than ten call sites. The CHECK_PTHREAD macro shown earlier is a reasonable wrapper for a command-line tool; a library should return the error instead of calling exit, because the decision to stop belongs to the application.


