Sub topic 5
Shared Memory in Node.js worker_threads
This chapter assumes you know how to start a Node.js worker with new Worker(...), can read CommonJS require syntax, and have read the earlier chapters on creating a SharedArrayBuffer and wrapping it in typed arrays.
Node.js gives you the same SharedArrayBuffer and Atomics globals as browsers. Its threads come from the built-in node:worker_threads module instead of the Web Worker API. Each worker runs its own V8 isolate and event loop, just as a browser worker does. You can share raw memory between those threads in the same way.
What Changes Compared to Browsers
| Concern | Browser | Node.js |
|---|---|---|
| Thread API | `new Worker(url)` | `new Worker(filename, options)` from `node:worker_threads` |
| Initial data | First `postMessage` call | `workerData` option or `postMessage` |
| Receiving messages | `self.onmessage` | `parentPort.on('message', ...)` |
| Cross-origin isolation | Required (COOP and COEP headers) | Not needed, because there are no origins |
| Feature check | `crossOriginIsolated` | Always available |
The security restriction from the previous chapter applies only to browsers. In Node.js, SharedArrayBuffer works with no setup.
Passing a SharedArrayBuffer Through workerData
Node.js clones workerData with the structured clone algorithm, the same one postMessage uses. A plain ArrayBuffer gets copied. A SharedArrayBuffer gets shared: the worker receives a new SharedArrayBuffer object that points at the same bytes. You don't list it in a transfer list.
The program below starts four workers from the same file. Each one adds 1 to a shared counter 100,000 times. The main thread prints the total after every worker has exited.
// counter.js — run with: node counter.js
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', () => {
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);
}
}The program always prints 400000. Atomics.add performs the read, the addition, and the write as one step that no other thread can interrupt. The next chapter shows what goes wrong if you write counter[0]++ instead.
Sharing Later with postMessage
You can also hand over a buffer after the worker has started. worker.postMessage(sab) and parentPort.postMessage(sab) both share the memory. They don't copy it.
// late-share.js — run with: node late-share.js
const { Worker, isMainThread, parentPort } = require('node:worker_threads');
if (isMainThread) {
const sab = new SharedArrayBuffer(4);
const view = new Int32Array(sab);
const worker = new Worker(__filename);
worker.on('message', () => {
console.log(Atomics.load(view, 0)); // 7
worker.terminate();
});
worker.postMessage(sab);
} else {
parentPort.on('message', (buf) => {
Atomics.store(new Int32Array(buf), 0, 7);
parentPort.postMessage('done');
});
}Common Errors
- Sending an
ArrayBufferand expecting it to be shared. The worker gets a copy, so its writes never reach the main thread. - Reading the result too early. Workers run alongside the main thread. Wait for an
exitormessageevent before you read the final value. - Wrapping a nested
Bufferslice. ABuffercreated withBuffer.from(sab)shares memory. ABufferfrom the pool or fromBuffer.allocdoes not.
Exercise
In counter.js, you replace new SharedArrayBuffer(4) with new ArrayBuffer(4) and leave everything else unchanged. What gets printed, and why?
Show answer
It throws a TypeError. Atomics.load requires an integer typed array, and in Node it accepts non-shared buffers, so the error actually appears in the workers. Each worker receives a cloned ArrayBuffer, and Atomics.add on it works but only changes the worker's private copy. The main thread's counter is never touched, so it prints 0.
Exercise
Why can a Node.js program use SharedArrayBuffer without the COOP and COEP headers that browsers require?
Show answer
Browsers require cross-origin isolation to stop pages from mounting timing attacks against cross-origin data loaded into the same process. A Node.js process has no web origins or untrusted embedded content, so this restriction doesn't apply and SharedArrayBuffer is always available.