← Runtimes
Runtimes

Data races and synchronization

Know which interleavings change the result, and what each tool prevents.

Choose synchronization around the shared operation and the invariant that its observers must see.

Outcome

Identify the interleaving that breaks a result, choose between atomic operations and locks, and protect invariants that span several values, knowing what each language’s memory model promises.

Terminology (6)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Data race
Conflicting accesses to the same memory by different threads, at least one a write, that are not ordered by the required synchronization. The precise rule depends on the language.
Race condition
A result that depends on how operations interleave, even when every access is synchronized.
Atomic operation
An operation other threads cannot observe half done, such as an atomic add or compare-and-exchange.
Lock (mutex)
Allows one holder at a time. Unlocking and a subsequent acquisition of that same mutex order the protected accesses when all participants follow the protocol.
Invariant
A condition required at observable operation boundaries, such as a constant combined stock total during rebalancing. Locks can hide intermediate states from observers.
Memory model
The language’s rules for which writes a thread’s reads may see, and what an unsynchronized program means.

Shared state and synchronization boundaries

Concurrent activities can access the same state at different points in an operation. An invariant is a condition that must hold when that operation is observed, such as a stock total matching the units available to sell. Reasoning about correctness means identifying both the state and the boundaries at which another participant may observe it.

A mutex gives cooperating participants exclusive access to a protected region; an atomic operation supplies an indivisible access or update. A memory model defines the ordering and visibility rules for those accesses. A data race violates a language’s synchronization rules, while a broader race condition can depend on scheduling even when individual accesses follow those rules.

01Lost updates

Each step can be safe while the sequence is not

A returned unit reaches the warehouse shelf but disappears from the order service’s count. The receiving code uses atomic reads and writes; the count is still wrong. Repairing that update exposes two further requirements: reserve only available stock, then report a consistent total while stock moves between warehouses.

Counting a received unit is three steps: read the count, add one, write it back. Two receiving stations that both read 41 both write 42, and one unit disappears from the count while it sits on the shelf. This program runs four stations as threads; each counts its 100,000 scans into one received count with an atomic load followed by an atomic store, and into another with a single atomic add.

main.ts
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
import { Worker, isMainThread, workerData, parentPort } from 'node:worker_threads';

// Each receiving station scans this many units of one item.
const SCANS = 100_000;

if (isMainThread) {
  const counters = new Int32Array(new SharedArrayBuffer(8));
  const workers = Array.from(
    { length: 4 },
    () =>
      new Promise((resolve) => {
        const worker = new Worker(process.argv[1]!, { workerData: counters.buffer });
        worker.once('message', resolve);
      })
  );
  Promise.all(workers).then(() => {
    console.log(`load then store: ${counters[0]} of 400000 units received`);
    console.log(`Atomics.add: ${counters[1]} of 400000 units received`);
  });
} else {
  const counters = new Int32Array(workerData as SharedArrayBuffer);
  for (let i = 0; i < SCANS; i++) Atomics.store(counters, 0, Atomics.load(counters, 0) + 1);
  for (let i = 0; i < SCANS; i++) Atomics.add(counters, 1, 1);
  parentPort!.postMessage('done');
}
terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
npx tsc --noEmit --strict main.ts && node main.ts
Four receiving stations each count 100,000 scanned units into each shared count using the supplied atomic operations. Assuming all workers finish normally without integer overflow, what can the totals show?

02Check, then act

A lock protects an invariant, not a variable

Some updates involve a decision: reserve units for an order only if the warehouse has that many. Checking under a lock and subtracting under a second lock is two critical sections; between them other threads pass the same check, the stock level goes negative, and the service has accepted orders it cannot ship. The decision and the update must happen under one continuous hold of the lock.

Once reservations finish, the warehouse rebalances the remaining units. Transfers change both levels; a report can see units in neither warehouse if the update or the snapshot releases its protection halfway through. Writers and readers must use a compatible protocol covering both values. One shared mutex or a set of locks held together can do this. Use a consistent acquisition order, or a deadlock-avoiding library operation such as std::scoped_lock. No fairness or completion deadline follows from that choice.

03What each language promises

Unsynchronized access means different things

Two Node worker threads add to the same aligned Int32Array element over a SharedArrayBuffer, using plain reads and writes without Atomics or a lock. What does JavaScript permit?

04Practice

Keep the stock levels consistent

The supplied batch workflow finishes receiving before reservations, then captures the remaining stock total. Rebalancing runs alongside the auditor, which must keep seeing that total. The methods contain native waits standing in for confirmation; there is no external warehouse service. Input counts are nonnegative and small enough that stock arithmetic fits the supplied integer types.

Stock levels under load

Four workers receive stock, then reserve orders. Finally, rebalancing overlaps a stock audit. Native waits stand in for external confirmation; protect the updates and snapshots without depending on a lucky schedule.

  1. easy · R-RACE-V4-1 Count every restock
  2. medium · R-RACE-V4-2 Never oversell
  3. hard · R-RACE-V4-3 Consistent totals
Check this idea later
A page-view counter does views.store(views.load() + 1) from many request threads. Under load it undercounts. What fixes it with the least change?
A ticketing service moves 50 seats from the box office’s allocation to the website’s, each allocation with its own lock, released between the two updates. A capacity report sums both. What can it see?
A C++ bool done is concurrently written by one thread and polled by another, with no synchronization ordering the conflicting accesses. What does the standard guarantee?
Sources
In the frontend Check which memory a worker actually shares. Optional

A receiving dashboard starts four browser workers. In this diagnostic, receiving-worker.ts has an ordinary module-local count: each worker counts 40 returned units, posts that number once, then closes. The display below ends at 40.

Each Worker has its own JavaScript global environment. No SharedArrayBuffer crosses this message boundary. Is this the same lost-update bug as the probe, and would making the worker’s local increment atomic account for all four reports?

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

import { useEffect, useState } from "react";

export default function ReceivingCount() {
  const [received, setReceived] = useState(0);

  useEffect(() => {
    const workers = Array.from({ length: 4 }, () => {
      const worker = new Worker(new URL("./receiving-worker.ts", import.meta.url));
      worker.onmessage = (event: MessageEvent<number>) => setReceived(event.data);

      return worker;
    });

    return () => workers.forEach((worker) => worker.terminate());
  }, []);

  return <output>{received} units received</output>;
}

The handler replaces the displayed count with one worker’s completed count. React state here belongs to the main page; it does not turn worker-local variables into shared memory. First decide whether reports are deltas or complete per-worker totals.

Sources: HTML: workers and their global scopes.

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.