Sub topic 16
Shared Memory with SharedArrayBuffer and Atomics
This chapter assumes you have read the earlier chapters on typed arrays, element types, and moving buffers between workers with postMessage. You should also know how to start a worker, either a browser Worker or Node.js worker_threads. The examples are written for Node.js, so you can run them without setting up an HTTP server.
Sharing Versus Transferring
The previous chapter moved an ArrayBuffer to a worker. Moving a buffer is cheap, but afterwards only one side owns the memory and the sender's copy is detached. A SharedArrayBuffer works differently. When you post one to a worker, both sides get a handle to the same bytes. Neither side is detached, and a write made by one thread can be seen by the other.
| Property | `ArrayBuffer` (transferred) | `SharedArrayBuffer` (shared) |
|---|---|---|
| Owners at once | One | Many |
| Sender after `postMessage` | Detached, `byteLength` is 0 | Still usable |
| Needs synchronization | No | Yes, use `Atomics` |
| Browser requirement | None | Cross-origin isolation |
| Typical use | Hand off a finished result | Counters, flags, ring buffers, parallel work on one dataset |
You never read or write a SharedArrayBuffer directly, just as with ArrayBuffer. You wrap it in a typed array or a DataView. The constructor takes the same length argument, and since ES2024 it can also be created growable: new SharedArrayBuffer(4, { maxByteLength: 64 }) followed by grow(). A shared buffer can grow but never shrink, because another thread might be reading the end of it.
Enabling SharedArrayBuffer in Browsers
Spectre-style timing attacks led browsers to restrict shared memory. A page can only construct SharedArrayBuffer when it is cross-origin isolated. To get that state, serve the document with these two headers:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corpCheck the state at runtime before you rely on it:
if (globalThis.crossOriginIsolated) {
const sab = new SharedArrayBuffer(16);
console.log(sab.byteLength); // 16
} else {
console.log('Shared memory unavailable; fall back to postMessage copies');
}Why Plain Reads and Writes Are Not Enough
Suppose four workers each run counter[0]++ 100,000 times on a shared Int32Array. The expression counter[0]++ performs three steps: read the value, add one, and write the result back. Two threads can read the same old value, and then one increment is lost. This is a data race, and the final total is usually below 400,000 and changes from run to run.
The engine and the CPU may also reorder ordinary memory operations. If one thread writes a payload and then sets a "ready" flag, another thread is not guaranteed to see the flag and the payload in that order. Atomics operations fix both problems. Each one runs as a single indivisible step, and atomic operations are sequentially consistent with each other, so every thread observes them in one agreed order.
The Atomics Toolkit
Atomics is a namespace object like Math. Its functions take an integer typed array, an index, and usually a value.
| Function | Effect | Returns |
|---|---|---|
| `load(ta, i)` | Read | Current value |
| `store(ta, i, v)` | Write | `v` |
| `add`, `sub`, `and`, `or`, `xor` | Read-modify-write | Old value |
| `exchange(ta, i, v)` | Replace | Old value |
| `compareExchange(ta, i, expected, v)` | Replace only if current equals `expected` | Old value |
| `wait(ta, i, v, timeout)` | Sleep while `ta[i] === v` | `"ok"`, `"not-equal"`, or `"timed-out"` |
| `waitAsync(ta, i, v, timeout)` | Non-blocking `wait` | `{ async, value }` |
| `notify(ta, i, count)` | Wake waiters on index `i` | Number woken |
The arithmetic functions accept Int8Array through Uint32Array plus BigInt64Array and BigUint64Array. They reject Float32Array, Float64Array, and Uint8ClampedArray with a TypeError. wait and waitAsync are stricter and only accept Int32Array or BigInt64Array over a shared buffer. Values are converted using the same wrapping rules you saw earlier, so Atomics.add on a Uint8Array holding 255 wraps to 0.
A Race-Free Counter
Save this as counter.js and run node counter.js. A SharedArrayBuffer passed in workerData is shared, not copied.
const { Worker, isMainThread, workerData } = require('node:worker_threads');
const WORKERS = 4;
const ITERATIONS = 100000;
if (isMainThread) {
const sab = new SharedArrayBuffer(4);
const counter = new Int32Array(sab);
let finished = 0;
for (let i = 0; i < WORKERS; i++) {
const w = new Worker(__filename, { workerData: sab });
w.on('exit', () => {
finished++;
if (finished === WORKERS) {
console.log(Atomics.load(counter, 0)); // 400000
}
});
}
} else {
const counter = new Int32Array(workerData);
for (let i = 0; i < ITERATIONS; i++) {
Atomics.add(counter, 0, 1);
}
}Replace Atomics.add(counter, 0, 1) with counter[0]++ and run it a few times. On a multi-core machine you will usually see totals below 400,000.
Compare-and-Swap Loops
Some updates have no matching Atomics function. A shared maximum is one example. The usual pattern is a compare-and-swap loop: read the current value, compute the new one, and call compareExchange. If it returns something other than what you read, another thread got there first, so retry with the newer value.
function atomicMax(ta, i, value) {
let current = Atomics.load(ta, i);
while (value > current) {
const previous = Atomics.compareExchange(ta, i, current, value);
if (previous === current) return; // our write won
current = previous; // someone else wrote; retry
}
}
const best = new Int32Array(new SharedArrayBuffer(4));
atomicMax(best, 0, 7);
atomicMax(best, 0, 3);
atomicMax(best, 0, 12);
console.log(Atomics.load(best, 0)); // 12Waiting and Notifying
Polling a flag in a loop wastes CPU. Atomics.wait puts the thread to sleep until another thread calls Atomics.notify on the same index. The value argument guards against a lost wake-up: if the slot already differs from the value you pass, wait returns "not-equal" at once instead of sleeping.
Save this as signal.js and run it with Node.js:
const { Worker, isMainThread, workerData, parentPort } = require('node:worker_threads');
if (isMainThread) {
const state = new Int32Array(new SharedArrayBuffer(8)); // [flag, payload]
const worker = new Worker(__filename, { workerData: state.buffer });
worker.on('message', (msg) => console.log(msg)); // "payload: 42"
setTimeout(() => {
Atomics.store(state, 1, 42); // write payload first
Atomics.store(state, 0, 1); // then publish the flag
Atomics.notify(state, 0);
}, 100);
} else {
const state = new Int32Array(workerData);
Atomics.wait(state, 0, 0); // sleeps while state[0] === 0
parentPort.postMessage(`payload: ${Atomics.load(state, 1)}`);
}The order of the stores matters. Because both are atomic, a thread that sees the flag set to 1 is guaranteed to see the payload written before it.
Common Errors
- Mixing atomic and plain access to the same slot. One
counter[0]++in otherwise atomic code brings the race back. Every access to shared, mutable state should go throughAtomics. - Calling
waiton the wrong type.Atomics.waiton aUint32Arrayor on a non-shared buffer throws aTypeError. - Forgetting to re-check after waking. A waiter can wake on a timeout or a notify meant for another condition. Wrap
waitin a loop that re-tests the condition. - Expecting
postMessageto detach a shared buffer. Listing aSharedArrayBufferin the transfer list throws aDataCloneError. Post it without a transfer list. - Assuming non-integer data is safe.
Float64Arraywrites to shared memory are not atomic. Store such values under a lock, or encode them as integers.
When to Use Shared Memory
Shared memory adds locking, header configuration, and harder debugging. Choose it when several threads need to read or update the same large dataset at the same time, or when message latency would dominate the work, as with audio worklets fed by a ring buffer or WebAssembly threads. If one side produces data and the other consumes it, transferring an ArrayBuffer is simpler and avoids races entirely.
Exercise
A worker runs Atomics.wait(state, 0, 0) where state[0] is already 1. What does the call return, and why does wait take that value argument at all?
Show answer
It returns "not-equal" immediately without sleeping. The value argument closes the gap between checking a condition and going to sleep: if another thread changed the slot and called notify before wait ran, a wait without the check would sleep forever and miss the wake-up.
Exercise
Write a function tryAcquire(lock) that takes an Int32Array over a SharedArrayBuffer, where index 0 is 0 when unlocked and 1 when locked. It should take the lock and return true only if the lock was free.
Show answer
function tryAcquire(lock) { return Atomics.compareExchange(lock, 0, 0, 1) === 0; } The call writes 1 only if the current value is 0, and returns the old value. If the old value was 0, this thread took the lock.
Exercise
Why does Atomics.add(new Float64Array(new SharedArrayBuffer(8)), 0, 1) fail, and what does it throw?
Show answer
Atomics operations only accept integer typed arrays, because hardware atomic instructions work on integer words. Passing a Float64Array throws a TypeError.