Sub topic 1
How JavaScript Runs Code in Parallel
Prerequisites
This chapter assumes you know ES2015+ syntax, ArrayBuffer and typed arrays such as Int32Array, the event loop and Promises, basic Web Workers or Node.js worker_threads, and HTTP response headers.
Agents and Message Passing
Each JavaScript thread is an agent. An agent has its own heap and its own event loop. A Web Worker or a Node.js worker thread is a separate agent that runs alongside the main thread. By default, postMessage copies data between agents with the structured clone algorithm, so neither side can see the other's changes. If you transfer an ArrayBuffer, the sender loses access to it.
Creating and Sharing a SharedArrayBuffer
When you post a SharedArrayBuffer, the browser does not copy or transfer it. Both agents get a handle to the same bytes.
// main.js
const sab = new SharedArrayBuffer(16);
const shared = new Int32Array(sab);
const worker = new Worker('worker.js');
worker.postMessage(sab);
worker.onmessage = () => {
console.log(Atomics.load(shared, 0)); // 42
};
// worker.js
self.onmessage = (event) => {
const shared = new Int32Array(event.data);
Atomics.store(shared, 0, 42);
self.postMessage('done');
};Enabling Shared Memory in Browsers with Cross-Origin Isolation
Browsers expose SharedArrayBuffer only to pages that are cross-origin isolated. This rule defends against Spectre-style timing attacks. Serve the top-level document with these headers:
Cross-Origin-Opener-Policy: same-origin
Cross-Origin-Embedder-Policy: require-corpCheck the result before you rely on shared memory:
if (!globalThis.crossOriginIsolated) {
console.warn('SharedArrayBuffer is unavailable: page is not cross-origin isolated');
}Reading and Writing Shared Memory Through Typed Arrays
A SharedArrayBuffer holds raw bytes. You read and write it through a typed array view, such as Int32Array or Uint8Array. Several views can cover the same buffer. Plain indexing (view[0] = 1) works, but other threads may not see those writes safely or in order. Use Atomics with integer views for anything another thread reads. The next chapter covers why.
Shared Memory in Node.js worker_threads
Node.js has no isolation requirement. You can pass the buffer in workerData or with postMessage:
const { Worker, isMainThread, workerData } = require('node:worker_threads');
if (isMainThread) {
const sab = new SharedArrayBuffer(4);
const view = new Int32Array(sab);
const w = new Worker(__filename, { workerData: sab });
w.on('exit', () => console.log(Atomics.load(view, 0))); // 7
} else {
Atomics.store(new Int32Array(workerData), 0, 7);
}Exercise
A page posts a SharedArrayBuffer to a worker, but new SharedArrayBuffer(16) throws ReferenceError in Chrome. What is the most likely cause, and how do you confirm it?
Show answer
The page is not cross-origin isolated, so the browser hides SharedArrayBuffer. Check globalThis.crossOriginIsolated. If it is false, serve the document with Cross-Origin-Opener-Policy: same-origin and Cross-Origin-Embedder-Policy: require-corp.
Exercise
How does posting an ArrayBuffer differ from posting a SharedArrayBuffer?
Show answer
An ArrayBuffer is copied, or moved if you list it as transferable. When it is moved, the sender can no longer use it. A SharedArrayBuffer is shared, so both agents read and write the same memory.