Skip to main content
Be Bitwise
CConcurrency in C

Part ofSystems Programming Companion, week 12

Threads with pthreads

Modern programs rarely do just one thing at a time. A web server juggles thousands of connections at once, a video encoder chews through frames in parallel, a database runs queries while flushing pages to disk. All of them lean on threads — lightweight execution contexts that share an address space but run independently.

On Unix-like systems, C programs get their threads from pthreads (POSIX threads). The C standard itself only gained threads in C11, with <threads.h>, but pthreads had been the de facto API for decades by then and is still what most code uses. Once you understand it deeply, every other threading model you meet will feel like a variation on the theme.

Creating a Thread

The core function is pthread_create:

c
#include <pthread.h>
#include <stdio.h>
void *worker(void *arg) {
printf("Hello from thread!\n");
return NULL;
}
int main() {
pthread_t thread;
int ret = pthread_create(&thread, NULL, worker, NULL);
if (ret != 0) {
fprintf(stderr, "Failed to create thread\n");
return 1;
}
pthread_join(thread, NULL);
printf("Thread finished\n");
return 0;
}

Breaking pthread_create apart:

  • First argument: a pointer to a pthread_t that'll receive the thread identifier.
  • Second argument: thread attributes (NULL for defaults). Stack size, scheduling policy, and detach state live here.
  • Third argument: the function the thread runs. Signature must be void *(*)(void *).
  • Fourth argument: an argument forwarded to that function.

pthread_join blocks the calling thread until the named thread exits. Skip it and main might race ahead, kill the process, and take the worker down with it before it finishes.

Passing Arguments to Threads

A thread function takes a single void *. To smuggle structured data through, allocate a struct and cast:

c
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int id;
int iterations;
} thread_args;
void *worker(void *arg) {
thread_args *args = (thread_args *)arg;
printf("Thread %d running %d iterations\n", args->id, args->iterations);
for (int i = 0; i < args->iterations; i++) {
// do work
}
free(args);
return NULL;
}
int main() {
pthread_t threads[4];
for (int i = 0; i < 4; i++) {
thread_args *args = malloc(sizeof(thread_args));
args->id = i;
args->iterations = (i + 1) * 1000;
pthread_create(&threads[i], NULL, worker, args);
}
for (int i = 0; i < 4; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
Common Pitfall

Never hand a thread a pointer to a stack variable that might vanish before the thread reads it. The classic version of this bug is passing &i straight out of a loop — by the time the thread peeks, i has already moved on. Heap-allocate or use a long-lived array.

Predict: this loop starts four threads, each printing the number it was given. What comes out?
c
void *worker(void *arg) {
printf("Thread got %d\n", *(int *)arg);
return NULL;
}
int main() {
pthread_t threads[4];
for (int i = 0; i < 4; i++) {
pthread_create(&threads[i], NULL, worker, &i);
}
for (int i = 0; i < 4; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}

Anything, and it changes from run to run. Every thread receives the same address, &i, and reads it whenever the scheduler gets round to it. A thread that starts late sees whatever i holds by then, so numbers get skipped and repeated: 1 2 3 4, 2 4 4 4, even 4 4 4 4, and now and again a lucky 0 1 2 3 that hides the bug. Worse, the first i stops existing when its loop ends. A slow thread may read the slot after the second loop's i has moved in, or after the compiler has reused it for something else entirely, which makes the read undefined behaviour.

The fix is to give each thread its own copy that lives at least as long as the thread does:

c
int ids[4];
for (int i = 0; i < 4; i++) {
ids[i] = i;
pthread_create(&threads[i], NULL, worker, &ids[i]);
}

Getting Return Values

Thread functions return void *. Pull the value out via pthread_join:

c
void *compute(void *arg) {
int *result = malloc(sizeof(int));
*result = 42;
return result;
}
int main() {
pthread_t t;
pthread_create(&t, NULL, compute, NULL);
void *retval;
pthread_join(t, &retval);
int *result = (int *)retval;
printf("Thread returned: %d\n", *result);
free(result);
return 0;
}

Thread-Local Storage

Sometimes each thread wants its own copy of a variable. C11 added the _Thread_local keyword (also thread_local via <threads.h>), and pthreads exposes pthread_key_create for thread-specific data:

c
#include <pthread.h>
#include <stdio.h>
_Thread_local int per_thread_counter = 0;
void *worker(void *arg) {
int id = *(int *)arg;
for (int i = 0; i < 1000; i++) {
per_thread_counter++;
}
printf("Thread %d counter: %d\n", id, per_thread_counter);
return NULL;
}
int main(void) {
pthread_t threads[3];
int ids[3] = {0, 1, 2};
for (int i = 0; i < 3; i++)
pthread_create(&threads[i], NULL, worker, &ids[i]);
for (int i = 0; i < 3; i++)
pthread_join(threads[i], NULL);
printf("Main thread counter: %d\n", per_thread_counter); // still 0
return 0;
}

Each thread gets its own per_thread_counter. Writes in one thread are invisible to the others.

Detached Threads

If you don't care about the return value or when the thread finishes, detach it:

c
pthread_t t;
pthread_create(&t, NULL, worker, NULL);
pthread_detach(t);
// No need to join - thread cleans up automatically when it finishes

Detached threads are handy for fire-and-forget work like logging or periodic cleanup. One catch: if main returns, every thread dies regardless. Detach is not immortality.

Compilation

pthreads requires linking with -pthread:

bash
gcc -pthread program.c -o program

That single flag both sets the right preprocessor macros and links the pthread library.

What Happens Under the Hood

Call pthread_create and on Linux the C library usually fires off the clone syscall (other systems have their equivalents). The result is a new execution context sharing the parent's virtual address space. Each thread gets its own stack (typically a 2-8 MB virtual reservation; pages are only committed as the stack grows) and inherits the heap, globals, and file descriptors.

Here's the split for main plus two workers. Everything in the shared box is reachable by every thread through an ordinary pointer, and that includes another thread's stack if you hand out its address, which is exactly the &i bug from earlier.

That sharing is both the power and the peril. It makes communication cheap but opens the door to data races — two threads touching the same memory at the same time, at least one of them writing. In C, that's undefined behaviour.

Next lesson: how to lock the door using synchronisation primitives.