Sharing Memory with SharedArrayBuffer and Atomics
Coordinate threads over shared memory using Atomics to avoid copying large buffers and prevent race conditions.
Why Shared Memory?
When you spin up a Worker in Node.js and call postMessage, the data you send is copied using the structured clone algorithm. For small messages that is fine, but for a large numeric buffer (millions of bytes) copying wastes CPU and memory.
- SharedArrayBuffer lets multiple threads read and write the same block of memory with zero copying.
- Atomics gives you safe, race-free operations on that memory.
This lesson shows how to coordinate threads over shared memory in a CPU-bound backend job.
ArrayBuffer vs SharedArrayBuffer
An ArrayBuffer is owned by one thread. When transferred to a worker, the sender loses access to it. A SharedArrayBuffer (SAB) is different: passing it to a worker shares the same backing store, so both threads see each other's writes.
You never read raw bytes directly. Instead you wrap the buffer in a typed array view such as Int32Array or Float64Array.
const sab = new SharedArrayBuffer(16);
const view = new Int32Array(sab);
console.log(view.length);
view[0] = 42;
console.log(view[0]);
console.log(sab.byteLength);All lessons in this course
- Why the Event Loop Stalls on CPU-Bound Work
- Spawning Worker Threads and Passing Messages
- Sharing Memory with SharedArrayBuffer and Atomics
- Building a Reusable Worker Pool for Throughput