Worker transfer lists and Atomics.add()
Node worker messages support three distinct memory behaviors: copying structured data, transferring ownership of an eligible ArrayBuffer, and sharing memory through SharedArrayBuffer. Choose the simplest ownership model that satisfies the task. A transfer list can move an ArrayBuffer to another thread, detaching the sender’s buffer and its views. Use explicitly allocated ArrayBuffers for predictable ownership; pooled Node Buffers may share underlying allocations and have different transfer behavior. SharedArrayBuffer instead permits both workers to access the same memory, so coordination matters. Atomics provides atomic operations on suitable integer typed arrays; a sequence of separate atomic operations does not automatically make a compound invariant atomic. Shared memory does not imply shared JavaScript objects or a sandbox. Do not read a transferred view as though it still owns bytes. Do not rely on unsynchronized increments to shared counters or assume Atomics makes arbitrary multi-step transactions safe. Sources: https://nodejs.org/download/release/v22.16.0/docs/api/worker_threads.html.
Formal Syntax & Structure
worker.postMessage(value, transferList); Atomics.add(typedArray, index, value)Working Example
import {Worker} from 'node:worker_threads';import {once} from 'node:events';const buffer=new ArrayBuffer(4);new Uint8Array(buffer).set([1,2,3,4]);const worker=new Worker(new URL('./worker.mjs',import.meta.url));try {const reply=once(worker,'message');worker.postMessage(buffer,[buffer]);console.log('sender bytes',buffer.byteLength);console.log('receiver sum',(await reply)[0]);}finally{await worker.terminate();}