Synchronisation Primitives
Threads share memory. That's their best feature and their worst one. Two threads reading and writing the same variable without coordination produces a data race — undefined behaviour that surfaces as wrong answers, crashes, or the truly mean kind of corruption that only appears under load.
Synchronisation primitives are how you prevent data races by enforcing ordering between threads.
Mutexes
A mutex (mutual exclusion) is the most basic synchronisation primitive. It guarantees that only one thread is inside a critical section at any moment:
#include <pthread.h>#include <stdio.h>
int counter = 0;pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
void *increment(void *arg) { for (int i = 0; i < 100000; i++) { pthread_mutex_lock(&lock); counter++; pthread_mutex_unlock(&lock); } return NULL;}
int main() { pthread_t t1, t2; pthread_create(&t1, NULL, increment, NULL); pthread_create(&t2, NULL, increment, NULL); pthread_join(t1, NULL); pthread_join(t2, NULL); printf("%d\n", counter); // Always 200000 return 0;}counter++ compiles to three separate operations under the covers: load, add one, store. Two threads can interleave those steps and lose updates outright. The mutex serialises the whole sequence, so only one thread touches it at a time.
PTHREAD_MUTEX_INITIALIZER is a static initializer for mutexes. For dynamically allocated mutexes, use pthread_mutex_init(&lock, NULL) and pthread_mutex_destroy(&lock) when done.
Condition Variables
A condition variable parks a thread to sleep until someone else signals the condition is true. Always paired with a mutex:
#include <pthread.h>#include <stdio.h>#include <stdbool.h>
pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;pthread_cond_t cond = PTHREAD_COND_INITIALIZER;bool data_ready = false;int shared_data = 0;
void *producer(void *arg) { pthread_mutex_lock(&lock); shared_data = 42; data_ready = true; pthread_cond_signal(&cond); pthread_mutex_unlock(&lock); return NULL;}
void *consumer(void *arg) { pthread_mutex_lock(&lock); while (!data_ready) { pthread_cond_wait(&cond, &lock); } printf("Received: %d\n", shared_data); pthread_mutex_unlock(&lock); return NULL;}The while loop around pthread_cond_wait matters. Condition variables suffer spurious wakeups — a thread can wake up even when no one signalled it. The loop re-checks the condition every time.
pthread_cond_wait atomically drops the mutex and parks the thread. On wakeup it grabs the mutex again before returning. That atomicity is the whole point: it shuts the window in which a checker could miss the signal between checking and sleeping.
The in-browser runner can't start threads, so try this one on paper first. Here's the skeleton of a bounded queue that several producers and consumers share. Producers must block while it's full, consumers while it's empty.
#define CAP 8
typedef struct { int items[CAP]; int head, tail, count; pthread_mutex_t lock; pthread_cond_t not_full; // signalled when a slot frees up pthread_cond_t not_empty; // signalled when an item arrives} BoundedQueue;
void bq_push(BoundedQueue *q, int value);int bq_pop(BoundedQueue *q);Write bq_push and bq_pop, then compare. Why two condition variables rather than one?
void bq_push(BoundedQueue *q, int value) { pthread_mutex_lock(&q->lock); while (q->count == CAP) // full: wait for a consumer pthread_cond_wait(&q->not_full, &q->lock); q->items[q->tail] = value; q->tail = (q->tail + 1) % CAP; q->count++; pthread_cond_signal(&q->not_empty); // wake one waiting consumer pthread_mutex_unlock(&q->lock);}
int bq_pop(BoundedQueue *q) { pthread_mutex_lock(&q->lock); while (q->count == 0) // empty: wait for a producer pthread_cond_wait(&q->not_empty, &q->lock); int value = q->items[q->head]; q->head = (q->head + 1) % CAP; q->count--; pthread_cond_signal(&q->not_full); // wake one waiting producer pthread_mutex_unlock(&q->lock); return value;}With a single condition variable, producers and consumers wait in the same line. A consumer's pthread_cond_signal might wake another consumer instead of the blocked producer it meant to reach; that consumer sees the queue still empty and goes back to sleep, and the producer is never woken. Two condition variables mean each signal reaches the kind of thread that can actually make progress. (One variable with pthread_cond_broadcast also works, at the cost of waking everybody every time.)
Read-Write Locks
When reads vastly outnumber writes, a plain mutex is overkill. A read-write lock lets readers pile in concurrently while still giving writers exclusive access:
#include <pthread.h>#include <stdio.h>
int shared_value = 0;pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER;
void *reader(void *arg) { pthread_rwlock_rdlock(&rwlock); printf("Read: %d\n", shared_value); pthread_rwlock_unlock(&rwlock); return NULL;}
void *writer(void *arg) { pthread_rwlock_wrlock(&rwlock); shared_value = 100; printf("Wrote: %d\n", shared_value); pthread_rwlock_unlock(&rwlock); return NULL;}Many threads can hold the read lock at once. The write lock is exclusive: while one thread holds it, no readers and no other writers get through.
Avoiding Deadlocks
A deadlock happens when two or more threads sit waiting for each other to release locks, forming a cycle nobody can break:
// Thread 1 // Thread 2pthread_mutex_lock(&lockA); pthread_mutex_lock(&lockB);pthread_mutex_lock(&lockB); pthread_mutex_lock(&lockA);// DEADLOCK: each thread holds one lock and waits for the otherDraw who holds what and who's waiting for what, and the problem becomes a loop you can trace with a finger. On the left is the code above. On the right, both threads lock A first: thread 2 queues behind thread 1 for A, thread 1 takes B unopposed, and the arrows end at a thread that can still run.
Ways to prevent deadlocks:
- Lock ordering: always acquire locks in the same order. If every thread locks A before B, no cycle can form.
- Try-lock: use
pthread_mutex_trylock. If it fails, drop everything you hold and retry. - Minimise lock scope: hold locks for the shortest time you can. No I/O, no expensive computation under the lock.
- Single lock: when feasible, one mutex beats several. Simpler code, fewer bugs.
// Safe: always lock A before Bvoid thread_work() { pthread_mutex_lock(&lockA); pthread_mutex_lock(&lockB); // critical section pthread_mutex_unlock(&lockB); pthread_mutex_unlock(&lockA);}pthread_mutex_trylock
Sometimes you want to try a lock without blocking:
if (pthread_mutex_trylock(&lock) == 0) { // Got the lock // ... critical section ... pthread_mutex_unlock(&lock);} else { // Lock is held by another thread; do something else}Handy for non-blocking algorithms or for back-off-style deadlock avoidance.
Barriers
A barrier holds threads until a specified number of them have all arrived:
pthread_barrier_t barrier;pthread_barrier_init(&barrier, NULL, NUM_THREADS);
void *worker(void *arg) { // Phase 1: compute locally do_local_work();
pthread_barrier_wait(&barrier); // All threads have finished phase 1
// Phase 2: combine results combine_results(); return NULL;}Call pthread_barrier_destroy(&barrier) once every thread is done with it. Barriers are an optional part of POSIX: Linux has them, but macOS doesn't provide pthread_barrier_t at all, so portable code sometimes builds its own from a mutex, a condition variable and a counter.
Barriers shine in phased parallel algorithms — parallel sorts, simulation steps, anything where everyone must finish phase N before anyone starts phase N+1.
Guidelines for Writing Correct Concurrent Code
- Identify shared state: anything two threads can both touch needs protection.
- Minimise sharing: thread-local data needs no synchronisation at all.
- Keep critical sections short: every cycle under a lock is a cycle of serialisation.
- Document your locking protocol: a comment explaining which lock guards which data is worth its weight in debugging hours.
- Test under load: concurrency bugs love contention. They often hide until you push.
- Run ThreadSanitizer: build with
-fsanitize=thread -g(GCC and Clang) and it reports data races as they happen, with the stack of both conflicting accesses.
Next lesson: atomic operations, synchronisation without locks.
Challenges
Use a mutex to protect a shared counter incremented by two threads. Each thread should increment it 100000 times. Print the final value.