Workspace

Threads, races and deadlock

3 day streakD

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.

BasicsLesson 1 of 615 min

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.

Figure 1.1

Lose an update, then prevent it

Thread A
  1. r = count
  2. r = r + 1
  3. count = r
register r = —
Thread B
  1. r = count
  2. r = r + 1
  3. count = r
register r = —
Shared memorycount = 0

Both threads will run count++ once. We expect 2.

Step 01 / 7
Step through two threads incrementing one counter. Without a lock, both load 0 and both store 1. With a mutex, thread B waits until thread A has stored, so the final value is 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.

async-race.tsTypeScript
// 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

Parallel tool calls

Harnesses classify tools as read-only or mutating, run reads concurrently and queue writes per resource.

Database counters

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.

Rate limit state

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.

A good place to start

Explore a pattern

A little guidance

Start with a pattern, read through a problem, and mark it solved when the idea clicks. Save anything you want to revisit.

New tutorials are added one at a time. Your bookmarks and solved checkmarks stay in this browser.

Explore the roadmap