How to Share Memory Between Worker Threads
Share memory between Node.js worker threads with SharedArrayBuffer and Atomics: build a safe counter, wait and notify, split an array and avoid data races.

Worker threads normally talk by copying messages, which is safe and simple but costs time and memory when the data is large. A 500 MB image buffer copied to four workers becomes 2 GB. A SharedArrayBuffer avoids that: it is one block of memory that several threads can read and write at the same time, with no copy. The price is that you take on a problem JavaScript otherwise spares you, which is concurrent access to the same bytes. This post shows how to create shared memory, why plain reads and writes race, how Atomics fixes it, how to wait and wake threads, and when to split work so threads never touch the same data at all. The samples use ES modules on Node.js 26, and they build on the basics in How to Use Worker Threads for CPU-Bound Work.
Copy, transfer and share
There are three ways to give a worker some data, and they differ in what the sender keeps.
| Method | What happens | Sender keeps it |
|---|---|---|
Copy (default postMessage) | A structured clone is made | yes, a separate copy |
| Transfer (transfer list) | Ownership moves to the receiver | no, the buffer is detached |
Share (SharedArrayBuffer) | Both sides see the same memory | yes, and so does the receiver |
Sharing is the only option where two threads can work on the same data at the same time. That is its strength and its danger. The [MDN reference on SharedArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) and the [Atomics reference](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Atomics) describe the language features, and Node.js passes them between workers through workerData or postMessage().
Create shared memory and give it to a worker
A SharedArrayBuffer is created with a byte length, and you read and write it through a typed array view. When you pass the buffer in workerData, it is shared, not copied.
import { Worker } from "node:worker_threads";
const shared = new SharedArrayBuffer(4);
const view = new Int32Array(shared);
const worker = new Worker(
`
const { workerData } = require("node:worker_threads");
const view = new Int32Array(workerData);
view[0] = 42;
`,
{ eval: true, workerData: shared },
);
worker.on("exit", () => {
console.log("main sees:", view[0]);
});main sees: 42The worker wrote 42 into index 0 of its own Int32Array, and the main thread read it back from its own view of the same buffer. Nothing was sent as a message. The main thread read it only after the exit event, which guarantees the worker had finished, so there was no overlap. That is the safest form of sharing: write in one place, read after the writer is done.
The eval: true option lets this sample live in one file. Real code puts the worker in its own module.
Why plain increments are wrong
Now let several threads change the same number. This looks innocent and is not.
import { workerData } from "node:worker_threads";
const view = new Int32Array(workerData);
for (let i = 0; i < 100000; i++) {
view[0] = view[0] + 1;
}import { Worker } from "node:worker_threads";
const shared = new SharedArrayBuffer(4);
const view = new Int32Array(shared);
const workers = Array.from(
{ length: 4 },
() => new Worker(new URL("./race-worker.js", import.meta.url), { workerData: shared }),
);
await Promise.all(
workers.map((w) => new Promise((resolve) => w.on("exit", resolve))),
);
console.log("expected 400000, got", view[0]);expected 400000, got 163827The final number is almost never 400000, and it is different on every run, so the value shown here is one plausible result, not a fixed one. The cause is that view[0] = view[0] + 1 is three steps: read the value, add one, write it back. Two threads can both read 7, both compute 8 and both write 8, losing one increment. This is a data race, and JavaScript's usual guarantee that only one piece of code runs at a time no longer protects you, because the threads really do run at the same time.
Atomics make the operation indivisible
The Atomics object provides operations that complete as a single step that no other thread can interrupt. Atomics.add(view, index, value) reads, adds and writes in one atomic action.
import { workerData } from "node:worker_threads";
const view = new Int32Array(workerData);
for (let i = 0; i < 100000; i++) {
Atomics.add(view, 0, 1);
}Run the same main file against this worker, with the file name changed in new URL(...):
expected 400000, got 400000Every increment is counted, on every run. The same family covers the other basic cases: Atomics.load() and Atomics.store() for reads and writes that are safe against reordering, Atomics.sub(), Atomics.and(), Atomics.or() and Atomics.xor() for arithmetic and bits, Atomics.exchange() to swap a value and Atomics.compareExchange() for a conditional update. Atomic operations only work on integer typed arrays such as Int32Array, Uint32Array and BigInt64Array. They do not work on Float64Array.
Use Atomics.load() rather than a plain read when another thread may be writing the cell. A plain read is allowed to see a stale value.
const view = new Int32Array(new SharedArrayBuffer(8));
Atomics.store(view, 0, 7);
console.log(Atomics.load(view, 0));
console.log(Atomics.compareExchange(view, 0, 7, 9));
console.log(Atomics.compareExchange(view, 0, 7, 11));
console.log(view[0]);7
7
9
9compareExchange(view, index, expected, replacement) writes the replacement only if the current value equals expected, and it always returns the value it found. The first call finds 7 and writes 9. The second expects 7 but finds 9, so it does not write and returns 9. This operation is the building block for locks and lock-free structures.
Waiting and waking with wait and notify
Spinning in a loop until a value changes wastes a core. Atomics.wait() puts the calling thread to sleep until another thread calls Atomics.notify() on the same cell. Use it in workers: it blocks the thread, so it is a poor idea on a main thread that must stay responsive.
import { workerData, parentPort } from "node:worker_threads";
const flag = new Int32Array(workerData);
const result = Atomics.wait(flag, 0, 0);
parentPort.postMessage({ result, flag: Atomics.load(flag, 0) });import { Worker } from "node:worker_threads";
const shared = new SharedArrayBuffer(4);
const flag = new Int32Array(shared);
const worker = new Worker(new URL("./waiter.js", import.meta.url), {
workerData: shared,
});
worker.on("message", (msg) => {
console.log(msg);
worker.terminate();
});
setTimeout(() => {
Atomics.store(flag, 0, 1);
Atomics.notify(flag, 0, 1);
}, 200);{ result: 'ok', flag: 1 }Atomics.wait(flag, 0, 0) means "sleep as long as the cell at index 0 still holds 0". The worker sleeps. After 200 milliseconds the main thread stores 1 and notifies one waiter. The worker wakes, and wait() returns the string "ok". It would return "not-equal" immediately if the value had already changed before the call, and "timed-out" if you gave a timeout in milliseconds as the fourth argument and it expired. Always store the new value before you notify, so a waiter that wakes sees it.
For the main thread there is Atomics.waitAsync(), which returns a promise instead of blocking, so you can wait without freezing the event loop.
Split the work so threads never collide
Atomics fix a race, and they are not free. The best way to deal with shared-memory hazards is to arrange that no two threads touch the same cell. Give each worker its own slice of one shared array.
import { workerData } from "node:worker_threads";
const { buffer, start, end } = workerData;
const numbers = new Float64Array(buffer);
for (let i = start; i < end; i++) {
numbers[i] = numbers[i] * numbers[i];
}import { Worker } from "node:worker_threads";
import { availableParallelism } from "node:os";
const size = 8;
const buffer = new SharedArrayBuffer(size * Float64Array.BYTES_PER_ELEMENT);
const numbers = new Float64Array(buffer);
numbers.set([1, 2, 3, 4, 5, 6, 7, 8]);
const threads = Math.min(availableParallelism(), 4);
const chunk = Math.ceil(size / threads);
const jobs = Array.from({ length: threads }, (_, i) => {
const start = i * chunk;
const end = Math.min(start + chunk, size);
return new Promise((resolve, reject) => {
const worker = new Worker(new URL("./slice-worker.js", import.meta.url), {
workerData: { buffer, start, end },
});
worker.on("error", reject);
worker.on("exit", resolve);
});
});
await Promise.all(jobs);
console.log(Array.from(numbers).join(", "));1, 4, 9, 16, 25, 36, 49, 64Each worker squares only the indexes from start to end, so no two workers read or write the same element, and no atomic operation is needed. The main thread reads the result after every worker has exited. The output is the same whether the machine has two cores or sixteen, because the slices cover the array exactly once. This is the pattern for parallel numeric work such as image filters, matrix operations and large array transforms.
Rules that keep shared memory safe
Prefer no sharing. Copy or transfer data when it is small enough. Sharing is for large data and for coordination.
Partition writes. If each thread owns a separate region, you avoid races without atomics.
**Use
Atomicsfor every shared cell that more than one thread writes,** and for reads of cells that another thread may be changing.Store before you notify, and always re-check the condition after waking, because a wake-up does not guarantee the state you wanted.
Share only typed arrays of fixed size. A
SharedArrayBuffercannot hold objects, strings or functions. To share structured data you design a binary layout, or keep the objects in one thread and share only numbers.Test under load. A race may pass a hundred runs and fail on the next. Run stress tests with more threads than cores.
When shared memory is the wrong tool
If the workers need to pass many small, varied messages, a normal message channel is clearer and fast enough, and bugs there are easier to find. If the shared state is complicated, such as a graph of objects, the cost of encoding it into bytes and guarding it with locks usually outweighs the saving. Reach for SharedArrayBuffer when the data is big, numeric and regular, or when threads must coordinate through a few counters and flags.


