Synchronization
Race conditions and critical sections; mutexes, spinlocks, semaphores, condition variables, monitors, read-write locks and atomics — with correct code in Java, Python and TypeScript.
When threads share data, the result can depend on the exact timing of their steps. That's a race condition, and it leads to the worst kind of bug: rare, timing-dependent and hard to reproduce. Synchronisation primitives let you control the interleaving.
A race in three instructions
count++ looks atomic but is really read → add → write:
class Counter {
int count = 0;
void inc() { count++; } // NOT thread-safe
}
// Two threads × 1,000,000 increments → usually much less than 2,000,000import threading
count = 0
def work():
global count
for _ in range(1_000_000):
count += 1 # read-modify-write; the GIL doesn't make this atomic
threads = [threading.Thread(target=work) for _ in range(2)]
for t in threads: t.start()
for t in threads: t.join()
print(count) # can be < 2,000,000// Single-threaded JS can't race on plain variables between statements,
// but async code can interleave between awaits:
let balance = 100;
async function withdraw(n: number) {
const b = balance; // read
await audit(); // another withdraw runs here!
balance = b - n; // write a stale value
}The critical-section problem
A critical section is code that accesses shared state. A correct solution must provide:
- Mutual exclusion — at most one thread inside at a time.
- Progress — if nobody is inside, someone who wants to enter eventually can.
- Bounded waiting — no thread waits forever (no starvation).
Mutex (lock)
class Counter {
private int count = 0;
private final ReentrantLock lock = new ReentrantLock();
void inc() {
lock.lock();
try { count++; }
finally { lock.unlock(); } // always unlock, even on exceptions
}
// Or the built-in monitor:
synchronized void inc2() { count++; }
}import threading
lock = threading.Lock()
count = 0
def inc():
global count
with lock: # acquire/release, exception-safe
count += 1// A minimal async mutex for code that awaits inside a critical section
class Mutex {
private last: Promise<void> = Promise.resolve();
async run<T>(fn: () => Promise<T>): Promise<T> {
const prev = this.last;
let release!: () => void;
this.last = new Promise((r) => (release = r));
await prev;
try { return await fn(); } finally { release(); }
}
}How locks work underneath: an atomic hardware instruction (compare-and-swap or test-and-set) claims the lock. If it's taken, a spinlock loops, which is good for very short waits on multicore machines and in kernels, while a blocking mutex asks the OS to put the thread to sleep. Linux implements blocking locks with futexes: no syscall at all when there's no contention.
Semaphores
A semaphore is a counter with two atomic operations: wait/P (decrement; block if it would go below zero) and signal/V (increment; wake a waiter).
- A binary semaphore (0/1) works like a lock.
- A counting semaphore limits concurrency to N, e.g. at most 10 simultaneous database connections.
Semaphore permits = new Semaphore(10);
permits.acquire();
try { callDatabase(); } finally { permits.release(); }sem = threading.BoundedSemaphore(10)
with sem:
call_database()// Limit concurrent fetches to 10 (a common async pattern)
async function mapLimit<T, R>(items: T[], limit: number, fn: (x: T) => Promise<R>) {
const results: R[] = [];
let i = 0;
const worker = async () => { while (i < items.length) { const k = i++; results[k] = await fn(items[k]); } };
await Promise.all(Array.from({ length: limit }, worker));
return results;
}Condition variables and monitors
A condition variable lets a thread wait (atomically releasing the lock) until some condition becomes true, and lets another thread wake it. Together with a lock this forms a monitor: Java's synchronized + wait/notifyAll is one.
class BoundedQueue<T> {
private final Deque<T> q = new ArrayDeque<>();
private final int cap;
BoundedQueue(int cap) { this.cap = cap; }
synchronized void put(T x) throws InterruptedException {
while (q.size() == cap) wait(); // ALWAYS wait in a while loop
q.addLast(x);
notifyAll();
}
synchronized T take() throws InterruptedException {
while (q.isEmpty()) wait();
T x = q.removeFirst();
notifyAll();
return x;
}
}
// In real code: java.util.concurrent.ArrayBlockingQueueimport threading
from collections import deque
class BoundedQueue:
def __init__(self, cap):
self.q, self.cap = deque(), cap
self.cv = threading.Condition()
def put(self, x):
with self.cv:
self.cv.wait_for(lambda: len(self.q) < self.cap)
self.q.append(x)
self.cv.notify_all()
def take(self):
with self.cv:
self.cv.wait_for(lambda: self.q)
x = self.q.popleft()
self.cv.notify_all()
return x
# In real code: queue.Queue(maxsize=cap)// Async equivalent: resolve waiting promises instead of sleeping threads
class AsyncQueue<T> {
private items: T[] = [];
private waiters: ((x: T) => void)[] = [];
put(x: T) {
const w = this.waiters.shift();
w ? w(x) : this.items.push(x);
}
take(): Promise<T> {
return this.items.length
? Promise.resolve(this.items.shift()!)
: new Promise((res) => this.waiters.push(res));
}
}Read-write locks
Many readers may hold the lock at the same time; a writer needs exclusive access. Great for read-heavy data such as configuration or caches (ReentrantReadWriteLock, StampedLock in Java). Watch out for writer starvation.
Atomics and lock-free code
For simple shared counters and flags, hardware atomic operations avoid locks entirely:
AtomicInteger count = new AtomicInteger();
count.incrementAndGet();
// CAS loop: retry until no one else changed the value in between
int old, next;
do { old = count.get(); next = Math.max(old, candidate); }
while (!count.compareAndSet(old, next));
LongAdder hits = new LongAdder(); // better under heavy contention# Python has no user-level atomics; use a Lock, or itertools.count()
# (whose next() is atomic in CPython because of the GIL).
import itertools
ids = itertools.count()
next(ids)// Shared memory between workers uses Atomics on a SharedArrayBuffer
const shared = new Int32Array(new SharedArrayBuffer(4));
Atomics.add(shared, 0, 1);
Atomics.compareExchange(shared, 0, 1, 2);Lock-free algorithms built on CAS (concurrent queues, ConcurrentHashMap) avoid blocking entirely but are hard to get right: beware the ABA problem and memory-ordering subtleties.
Choosing a primitive
| Need | Use |
|---|---|
| Protect shared state | Mutex / synchronized / with lock |
| Limit concurrency to N | Counting semaphore |
| Wait until a condition holds | Condition variable (or a blocking queue) |
| Many readers, few writers | Read-write lock |
| A single counter or flag | Atomic variable |
| Hand work between threads | A concurrent queue — usually the best choice |
- Race conditions come from unsynchronised read-modify-write on shared data.
- Critical sections need mutual exclusion, progress and bounded waiting.
- Mutexes for exclusion, semaphores for counting, condition variables for waiting on state.
- Always wait in a
whileloop; always release locks infinallyor awithblock. - Atomics and CAS give lock-free counters; queues and immutability avoid sharing entirely.
QMutex vs semaphore?easy
A mutex provides mutual exclusion and has an owner: only the thread that locked it may unlock it. A semaphore is a counter that allows up to N concurrent holders and can be signalled by any thread, which makes it suitable for signalling and resource pools.
QIs i++ atomic in Java if i is volatile?medium
No. volatile guarantees visibility and ordering, but i++ is still a read, an add and a write. Use AtomicInteger or a lock.
QWhen is a spinlock better than a blocking mutex?hard
When critical sections are very short (shorter than the cost of sleeping and waking, a few microseconds), on multicore machines, and where sleeping isn't allowed (interrupt handlers in kernels). On a single core, or with long hold times, spinning wastes CPU.