Learn C
#include "advanced/pthreads.h"

Multithreading with pthreads in C

#concept

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.

#how it works
1

Create and join

pthread_create(&t, NULL, work, arg); starts; pthread_join(t, &ret); waits and collects — join every thread you start.

2

Shared memory races

Two threads touching one variable with a write and no ordering is UB — not just wrong answers, any behavior.

3

Mutex discipline

pthread_mutex_lock/unlock around shared updates; init once, destroy at end — and keep critical sections tiny.

4

Link -pthread

gcc app.c -pthread — defines macros and links the thread library together; -lpthread alone misses the defines.

#example
#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;
}
Output
30
1Two threads launch running add with pointers to their own arguments.
2The mutex serializes total += n — no interleaving can lose an addition.
3Both joins complete before printing, so 10 + 20 = 30 exactly.
#use cases
Parallelizing independent chunks across cores
Protecting shared counters and caches with mutexes
Joining every created thread before using its results
Linking and defining correctly with single -pthread flag

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in C yourself — building beats watching.