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.
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');
}
npx tsc --noEmit --strict main.ts && node main.ts
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
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.
Check this idea later
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?
"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.
Sign in to keep your read marks on every device. Sign in
Was this helpful?