0
0
Node.jsframework~5 mins

SharedArrayBuffer for shared memory in Node.js

Choose your learning style9 modes available
Introduction
SharedArrayBuffer lets different parts of a program share the same memory space. This helps them work together faster without copying data.
When you want multiple threads or workers to read and write the same data quickly.
When you need to share large data like images or audio between workers without copying.
When you want to build fast communication between parts of your program.
When you want to avoid delays caused by sending messages with copies of data.
When you want to coordinate tasks by sharing flags or counters in memory.
Syntax
Node.js
const sharedBuffer = new SharedArrayBuffer(byteLength);
const sharedArray = new Uint8Array(sharedBuffer);
byteLength is the size in bytes of the shared memory you want.
You use typed arrays like Uint8Array or Int32Array to read and write the shared memory.
Examples
Create a 16-byte shared buffer and set the first byte to 42.
Node.js
const sharedBuffer = new SharedArrayBuffer(16);
const sharedArray = new Uint8Array(sharedBuffer);
sharedArray[0] = 42;
Edge case: zero-length buffer means no shared memory.
Node.js
const sharedBuffer = new SharedArrayBuffer(0);
// This creates an empty shared buffer with no bytes.
Using Int32Array to store a 32-bit integer in shared memory.
Node.js
const sharedBuffer = new SharedArrayBuffer(4);
const sharedArray = new Int32Array(sharedBuffer);
sharedArray[0] = 123456;
Sample Program
This program shows how main thread and worker share a counter using SharedArrayBuffer. The worker increments the counter and main thread prints the updated value.
Node.js
import { Worker, isMainThread, parentPort } from 'node:worker_threads';

if (isMainThread) {
  // Main thread creates shared memory
  const sharedBuffer = new SharedArrayBuffer(4); // 4 bytes for one Int32
  const sharedArray = new Int32Array(sharedBuffer);
  sharedArray[0] = 0; // Initialize counter to 0

  // Create a worker and pass the shared buffer
  const worker = new Worker(new URL(import.meta.url));
  worker.postMessage(sharedBuffer);

  // Listen for messages from worker
  worker.on('message', () => {
    console.log('Main thread sees counter:', sharedArray[0]);
  });
} else {
  // Worker thread
  parentPort.once('message', (sharedBuffer) => {
    const sharedArray = new Int32Array(sharedBuffer);
    // Increment the shared counter
    Atomics.add(sharedArray, 0, 1);
    // Notify main thread
    parentPort.postMessage('done');
  });
}
OutputSuccess
Important Notes
Using Atomics methods like Atomics.add is important to avoid race conditions when multiple threads change shared memory.
SharedArrayBuffer size must be a nonnegative integer; zero size means no shared memory.
SharedArrayBuffer is useful when you want fast, low-level communication between threads without copying data.
Summary
SharedArrayBuffer creates memory that multiple threads can access together.
Use typed arrays to read and write shared memory.
Use Atomics to safely change shared data without conflicts.