Multithreading with pthreads in C
POSIX threads (pthreads) run functions concurrently: pthread_create launches with a start routine plus one void* argument, pthread_join waits for completion and collects the return pointer. Threads share the entire address space, so unsynchronized shared access is a data race (undefined behavior), fixed with pthread_mutex_t plus lock/unlock pairs.
Higher-level needs map to the same primitives: condition variables for signaling, thread-local storage for per-thread state, barriers for rendezvous. Link with -pthread (compile and link flag in one), and prefer few long-lived threads over create-per-task churn.
Create and join
pthread_create(&t, NULL, work, arg); starts; pthread_join(t, &ret); waits and collects — join every thread you start.
Shared memory races
Two threads touching one variable with a write and no ordering is UB — not just wrong answers, any behavior.
Mutex discipline
pthread_mutex_lock/unlock around shared updates; init once, destroy at end — and keep critical sections tiny.
Link -pthread
gcc app.c -pthread — defines macros and links the thread library together; -lpthread alone misses the defines.
#include <stdio.h>#include <pthread.h> int total = 0;pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER; void *add(void *arg) { int n = *(int *)arg; pthread_mutex_lock(&lock); total += n; pthread_mutex_unlock(&lock); return NULL;} int main(void) { int a = 10, b = 20; pthread_t t1, t2; pthread_create(&t1, NULL, add, &a); pthread_create(&t2, NULL, add, &b); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("%d\n", total); return 0;}Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in C yourself — building beats watching.