Threads, races and deadlock
Two threads touching the same memory can interleave in ways that lose updates. Learn why count++ is three steps, how a mutex fixes it, and how two mutexes can freeze a program.
A thread is an independent sequence of execution inside a process. Threads share memory, which makes communication cheap and correctness hard. The scheduler can pause a thread between any two machine instructions and run another one.
A race in three instructions
count++ looks atomic but compiles to three steps: load the value into a register, add one, store it back. If two threads interleave those steps, both load the same old value and one increment disappears. This is a data race, and it is invisible in testing until load arrives.
Lose an update, then prevent it
r = countr = r + 1count = r
r = countr = r + 1count = r
Both threads will run count++ once. We expect 2.
Mutexes and atomics
A mutex lets only one thread into a critical section at a time. An atomic operation such as fetch-and-add does the whole read-modify-write as one indivisible hardware instruction, which is faster for a single counter. Use atomics for single values and a mutex when several values must change together.
Deadlock
Thread A holds lock 1 and waits for lock 2. Thread B holds lock 2 and waits for lock 1. Neither can continue. Deadlock needs four conditions at once: mutual exclusion, hold and wait, no preemption, and a circular wait. Break any one. The usual fix is a global lock order: always take lock 1 before lock 2.
// Single-threaded JavaScript still races across await points.
let balance = 100;
async function withdraw(amount: number) {
const current = balance; // read
await audit(amount); // another call runs here
balance = current - amount; // write based on a stale read
}
await Promise.all([withdraw(30), withdraw(50)]);
console.log(balance); // 50, not 20
// Fix: serialise access to the shared state
let queue = Promise.resolve();
const withLock = <T>(fn: () => Promise<T>) => (queue = queue.then(fn, fn)) as Promise<T>;Every await is a point where other code can run, so read-await-write is a race even without threads.
Where you will meet it
Harnesses classify tools as read-only or mutating, run reads concurrently and queue writes per resource.
UPDATE t SET n = n + 1 is atomic in the database. Reading n, adding one in the app and writing it back is a lost update under load.
A token bucket shared across async handlers needs atomic updates, or concurrent requests all see a full bucket.
Check yourself
Answer out loud before you open each one.
Why can count++ lose updates across threads?
It is a load, an add and a store. Two threads can both load the old value before either stores.
Can single-threaded JavaScript have a race condition?
Yes. Other code runs at every await, so a read before an await and a write after it can use stale data.
Name the usual way to prevent deadlock.
Acquire locks in one global order, which breaks the circular wait.
Try it
Run two Node worker_threads that each add 1,000,000 to a plain Int32Array slot of a SharedArrayBuffer. Print the result, then switch to Atomics.add and compare.