pthreads
POSIX threads (pthreads) are the standard C API for threads on Unix-like systems. pthread_create starts a function on a new thread. pthread_join waits for it to finish.
Detailed Explanation
ISO C11 added <threads.h>, but the API you will actually call on Linux and macOS is pthreads. You link with -pthread. The handle is pthread_t. The start routine has type void * (*)(void *). The argument is a pointer you supply; the return value is a pointer join receives.
pthread_t t;
pthread_create(&t, NULL, worker, arg);
pthread_join(t, &result);
NULL attributes means defaults: joinable, default stack, default scheduling. A joinable thread that nobody joins leaks an OS thread slot (a zombie thread). pthread_detach lets it clean up itself; then you cannot join. Pick one.
The start function's void * argument is how you pass more than one value: point it at a struct. That struct must outlive the thread's first read of it. A stack struct in the creating function is a dangling pointer the moment that function returns. Heap-allocate the argument, or wait until the worker has copied what it needs.
Shared data needs a defined protocol: a mutex, atomics, or confinement to one thread. Starting two threads that both increment an int without protection is a data race. pthreads will not stop you.
Cancellation, thread-specific data, realtime scheduling, and process-shared mutexes exist and are easy to misuse. Most application code needs create, join or detach, mutexes, and condition variables. Windows has a different API (CreateThread, SRW locks). Portable projects hide the difference behind a thin wrapper or use C11 threads where they exist.
main returning ends the process and cuts down every thread. Join workers you care about, or have them detach and finish before you exit.
Code Examples
#include <pthread.h>
#include <stdio.h>
static void *worker(void *arg)
{
int n = *(int *)arg;
printf("%d\n", n * 2); /* prints: 42 */
return NULL;
}
int main(void)
{
int arg = 21;
pthread_t t;
if (pthread_create(&t, NULL, worker, &arg) != 0) {
return 1;
}
if (pthread_join(t, NULL) != 0) {
return 1;
}
return 0;
}#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
struct Job { int id; };
static void *run(void *arg)
{
struct Job *job = arg;
printf("job %d\n", job->id);
free(job);
return NULL;
}
int main(void)
{
struct Job *job = malloc(sizeof *job);
if (job == NULL) {
return 1;
}
job->id = 1;
pthread_t t;
if (pthread_create(&t, NULL, run, job) != 0) {
free(job);
return 1;
}
pthread_join(t, NULL);
return 0;
}Common Gotchas
Passing `&local` into `pthread_create` and returning from that function before the worker reads it is a data race and a dangling pointer
keep the storage alive, or copy on the heap.
A joinable thread that is never joined leaks
join or detach.
Returning from `main` kills every thread
join the ones whose work you still need.
Compile and link with `-pthread`
declaring the header is not enough on some toolchains.