Sub topic 16
Shared Memory with SharedArrayBuffer and Atomics
This chapter assumes you know typed arrays over an ArrayBuffer and how postMessage transfers a buffer to a worker. It also assumes you have basic experience with Web Workers or Node's worker_threads.
Sharing Instead of Moving
A transferred ArrayBuffer has one owner at a time. Once you send it, the sender's copy is detached. A SharedArrayBuffer works differently. When you post it to a worker, both sides get a handle to the same memory, and writes from one thread are visible to the other. You read and write it through typed arrays in the usual way.
// Requires a cross-origin isolated context in browsers
const sab = new SharedArrayBuffer(4);
const counter = new Int32Array(sab);
Atomics.add(counter, 0, 1);
console.log(Atomics.load(counter, 0)); // 1Why Atomics Exist
Shared memory leads to data races. counter[0]++ is really three steps: read, add, write. If two threads read the same old value, one increment is lost. The Atomics object runs each operation as one indivisible step on an integer typed array (Int8Array through BigUint64Array). Float arrays are not allowed.
| Operation | Purpose |
|---|---|
| `Atomics.load` / `Atomics.store` | Read or write without tearing, with ordering guarantees |
| `Atomics.add`, `sub`, `and`, `or`, `xor` | Read-modify-write; returns the old value |
| `Atomics.exchange` | Swap in a new value |
| `Atomics.compareExchange` | Write only if the current value matches an expected one |
| `Atomics.wait` / `Atomics.notify` | Sleep until another thread signals (`Int32Array` or `BigInt64Array` only) |
The Node script below runs as shown with node counter.mjs. Four threads each increment a shared counter 100,000 times:
// counter.mjs
import { Worker, isMainThread, workerData } from 'node:worker_threads';
if (isMainThread) {
const sab = new SharedArrayBuffer(4);
const counter = new Int32Array(sab);
const workers = [];
for (let i = 0; i < 4; i++) {
workers.push(new Worker(new URL(import.meta.url), { workerData: sab }));
}
await Promise.all(workers.map((w) => new Promise((r) => w.on('exit', r))));
console.log(Atomics.load(counter, 0)); // 400000
} else {
const counter = new Int32Array(workerData);
for (let i = 0; i < 100000; i++) Atomics.add(counter, 0, 1);
}If you replace Atomics.add(counter, 0, 1) with counter[0]++, the total usually comes out below 400000.
Common Errors
SharedArrayBuffer is not definedin a browser. After the Spectre attacks, browsers expose it only to pages that are cross-origin isolated. The page must be served withCross-Origin-Opener-Policy: same-originandCross-Origin-Embedder-Policy: require-corp. You can checkself.crossOriginIsolatedat runtime.Atomics.waitthrows on the main thread. Browsers block it there because it would freeze the UI. Use it in workers, or useAtomics.waitAsyncwhere it is supported.- Mixing plain and atomic access. If one thread writes with
counter[0] = xwhile another usesAtomics, the ordering guarantees no longer hold. UseAtomicsfor every access to shared state. - Using it where transfer is enough. If only one thread needs the data at a time, transferring an
ArrayBufferis simpler and has no race risk.
Exercise
Two workers each run Atomics.add(view, 0, 5) once on a shared Int32Array that starts at 0. Worker A's call returns 0. What does Worker B's call return, and what is the final value?
Show answer
Worker B's call returns 5, the value just before its own add. The final value is 10. Each Atomics.add returns the old value and applies the whole update in one step.
Exercise
Why can't you use Atomics.add on a Float64Array view of a SharedArrayBuffer?
Show answer
Atomics operations accept only integer typed arrays. Float arrays throw a TypeError.