Synchronization — Races, Mutexes, Semaphores
Race conditions and critical sections, Peterson's algorithm, hardware atomics (test-and-set, CAS), spinlocks vs mutexes, semaphores, condition variables, monitors, read-write locks, futexes, memory ordering and lock-free basics.
The problem: shared mutable state
When threads share data and at least one writes, the order of interleaved instructions decides the result. That's a race condition.
#include <pthread.h>
#include <stdio.h>
long counter = 0;
void *inc(void *arg) {
for (int i = 0; i < 1000000; i++)
counter++; // load → add → store: NOT atomic
return NULL;
}
int main(void) {
pthread_t a, b;
pthread_create(&a, NULL, inc, NULL);
pthread_create(&b, NULL, inc, NULL);
pthread_join(a, NULL);
pthread_join(b, NULL);
printf("%ld\n", counter); // expected 2000000, typically ~1.1–1.9 million
}
import threading
counter = 0
def inc():
global counter
for _ in range(1_000_000):
counter += 1 # LOAD, ADD, STORE bytecodes: can interleave between threads
ts = [threading.Thread(target=inc) for _ in range(2)]
for t in ts: t.start()
for t in ts: t.join()
print(counter) # can be < 2,000,000 even with the GIL
Critical sections
A critical section is code that accesses shared state and must not be executed by more than one thread at once. A correct solution needs:
- Mutual exclusion
- Progress (no needless blocking)
- Bounded waiting (no starvation)
Software solution: Peterson's algorithm (two threads)
bool flag[2] = {false, false}; // flag[i]: thread i wants to enter
int turn; // whose turn it is to yield
void lock(int i) {
int j = 1 - i;
flag[i] = true; // I want in
turn = j; // but you go first if you also want in
while (flag[j] && turn == j) ; // busy-wait
}
void unlock(int i) { flag[i] = false; }
It satisfies all three requirements in theory — but fails on modern CPUs without memory barriers, because stores and loads can be reordered. It's taught to show the requirements; real code uses hardware atomics.
Hardware support: atomic instructions
| Instruction | Semantics |
|---|---|
| Test-and-set | atomically set a flag to 1 and return the old value |
| Compare-and-swap (CAS) | atomically: if *p == expected then *p = new; return success |
| Fetch-and-add | atomically add and return the old value (lock xadd) |
| Load-linked / store-conditional | ARM/RISC-V pair: store succeeds only if no one wrote since the load |
A spinlock from test-and-set
#include <stdatomic.h>
atomic_flag lock = ATOMIC_FLAG_INIT;
void spin_lock(void) { while (atomic_flag_test_and_set(&lock)) { /* spin */ } }
void spin_unlock(void) { atomic_flag_clear(&lock); }
Atomic counter without a lock
#include <stdatomic.h>
atomic_long counter = 0;
// in each thread:
atomic_fetch_add(&counter, 1); // always 2,000,000 at the end
AtomicLong counter = new AtomicLong();
counter.incrementAndGet(); // CAS loop under the hood (or LOCK XADD)
// LongAdder is even faster under heavy contention (striped counters)
Mutex (lock)
A mutex provides mutual exclusion with ownership: only the locker unlocks. Contended waiters sleep instead of spinning.
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
void *inc(void *arg) {
for (int i = 0; i < 1000000; i++) {
pthread_mutex_lock(&m);
counter++; // critical section
pthread_mutex_unlock(&m);
}
return NULL;
}
lock = threading.Lock()
def inc():
global counter
for _ in range(1_000_000):
with lock: # acquire/release, even if an exception is raised
counter += 1
private final Object lock = new Object();
private long counter;
void inc() {
synchronized (lock) { // or a ReentrantLock with try/finally
counter++;
}
}
Spinlock vs mutex
| Spinlock | Mutex | |
|---|---|---|
| Waiting | busy-loop on CPU | sleep in kernel (futex) |
| Best when | critical section ≪ context switch, holder on another core | longer sections, possible blocking |
| Can be used in interrupt context | yes | no (can't sleep) |
| Single-core machine | wasteful | fine |
Lock variants
- Recursive (reentrant) mutex — the owner can lock it again (Java
synchronized,ReentrantLock, PythonRLock). - Try-lock / timed lock — give up instead of blocking forever (deadlock avoidance).
- Read-write lock — many readers or one writer.
- Fair lock — FIFO hand-off; prevents starvation at the cost of throughput.
Semaphores
Dijkstra's semaphore is an integer with two atomic operations:
wait(S) / P / down: while S <= 0: block; S = S - 1
signal(S)/ V / up: S = S + 1; wake one blocked waiter (if any)
| Use | Initial value | Pattern |
|---|---|---|
| Mutual exclusion (binary) | 1 | wait; critical section; signal |
| Limit concurrency to N | N | e.g. at most 10 concurrent DB calls |
| Signalling / ordering | 0 | thread A does work then signal; thread B waits before continuing |
#include <semaphore.h>
sem_t slots;
sem_init(&slots, 0, 10); // at most 10 concurrent users
void use_connection(void) {
sem_wait(&slots); // blocks when all 10 are in use
/* ... use a pooled connection ... */
sem_post(&slots);
}
slots = threading.BoundedSemaphore(10)
def use_connection():
with slots:
... # at most 10 threads in here at once
Condition variables and monitors
Locks protect data; condition variables let threads wait for the data to reach a certain state without busy-waiting.
pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t ready_cv = PTHREAD_COND_INITIALIZER;
bool ready = false;
void *waiter(void *arg) {
pthread_mutex_lock(&m);
while (!ready) // ALWAYS a loop
pthread_cond_wait(&ready_cv, &m); // atomically unlock + sleep; relock on wake
/* ... proceed ... */
pthread_mutex_unlock(&m);
return NULL;
}
void *setter(void *arg) {
pthread_mutex_lock(&m);
ready = true;
pthread_cond_signal(&ready_cv); // or broadcast to wake all
pthread_mutex_unlock(&m);
return NULL;
}
class Gate {
private boolean open = false;
synchronized void await() throws InterruptedException {
while (!open) wait(); // monitor wait: releases the object's lock
}
synchronized void open() {
open = true;
notifyAll();
}
}
A monitor = mutex + condition variables + the data they protect, with the compiler/runtime guaranteeing the lock is held inside its methods. Java objects are monitors.
Mesa vs Hoare semantics: with Hoare semantics the signalled thread runs immediately; with Mesa semantics (all real systems) it's merely made runnable, so the condition may be false again by the time it runs — another reason for the while loop.
Read-write locks
ReadWriteLock rw = new ReentrantReadWriteLock();
Map<String, String> config = new HashMap<>();
String get(String k) {
rw.readLock().lock();
try { return config.get(k); } finally { rw.readLock().unlock(); }
}
void put(String k, String v) {
rw.writeLock().lock();
try { config.put(k, v); } finally { rw.writeLock().unlock(); }
}
Watch for writer starvation (choose a fair or writer-preferring lock) and remember RW locks are slower than plain mutexes for very short sections.
Memory ordering (the part most people miss)
CPUs and compilers reorder instructions. Without synchronisation, this "obviously correct" code can print 0:
int data = 0; bool ready = false; // plain, non-atomic
// Thread 1 // Thread 2
data = 42; while (!ready) ;
ready = true; printf("%d", data); // may print 0, or loop forever
Fix with release/acquire atomics (or a lock):
atomic_bool ready = false;
// Thread 1
data = 42;
atomic_store_explicit(&ready, true, memory_order_release);
// Thread 2
while (!atomic_load_explicit(&ready, memory_order_acquire)) ;
printf("%d", data); // guaranteed 42
- Release store: earlier writes can't move after it.
- Acquire load: later reads can't move before it.
- Sequentially consistent (default for C++/Java atomics and Java
volatile): one global order — simplest to reason about.
Lock-free and wait-free
- Lock-free: some thread always makes progress (CAS retry loops). No deadlocks; a preempted thread can't block others.
- Wait-free: every thread finishes in a bounded number of steps.
- Examples:
java.util.concurrent.ConcurrentLinkedQueue(Michael–Scott queue), atomic counters, RCU in the Linux kernel. - Hazards: ABA problem, memory reclamation, and subtle ordering bugs. Prefer well-tested libraries.
Choosing a primitive
| Need | Use |
|---|---|
| Protect a small shared structure | mutex (synchronized, Lock, std::mutex) |
| Single counter / flag | atomic |
| Limit concurrency to N | counting semaphore |
| Wait until a condition holds | condition variable (with a mutex) or a higher-level queue |
| Read-mostly data | RW lock, RCU, copy-on-write + atomic swap |
| Hand off work between threads | blocking queue / channel (best: no manual locking at all) |
| Coordinate phases | barrier, CountDownLatch, WaitGroup |
Common synchronisation bugs
- Forgetting to unlock on an error path → use RAII (
std::lock_guard),try/finally,with. - Locking different locks for the same data → no mutual exclusion at all.
- Check-then-act outside the lock (
if map.contains(k): map.get(k)). - Holding a lock while doing I/O or calling unknown code → contention, deadlocks.
- Double-checked locking without volatile (broken singleton initialisation in old Java/C++).
- Deadlock from inconsistent lock ordering → next chapters.
Interview questions
Answer out loud first, then open the model answer. Mark a question confident only when you could explain it to an interviewer without notes.