Introduction
SharedArrayBuffer lets different parts of a program share the same memory space. This helps them work together faster without copying data.
Jump into concepts and practice - no test required
const sharedBuffer = new SharedArrayBuffer(byteLength); const sharedArray = new Uint8Array(sharedBuffer);
const sharedBuffer = new SharedArrayBuffer(16); const sharedArray = new Uint8Array(sharedBuffer); sharedArray[0] = 42;
const sharedBuffer = new SharedArrayBuffer(0); // This creates an empty shared buffer with no bytes.
const sharedBuffer = new SharedArrayBuffer(4); const sharedArray = new Int32Array(sharedBuffer); sharedArray[0] = 123456;
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'); }); }
SharedArrayBuffer in Node.js?SharedArrayBuffer is designed to create a block of memory that can be shared between multiple threads or workers.SharedArrayBuffer.SharedArrayBuffer of 1024 bytes in Node.js?SharedArrayBuffer must be created with the new keyword and a size in bytes as argument.new SharedArrayBuffer(1024), which is correct. const sab = SharedArrayBuffer(1024); misses new. const sab = new SharedArrayBuffer(); misses size argument. const sab = SharedArrayBuffer.new(1024); uses invalid syntax.new with size in bytes [OK]const sab = new SharedArrayBuffer(4); const int32 = new Int32Array(sab); int32[0] = 10; Atomics.add(int32, 0, 5); console.log(int32[0]);
int32[0] is set to 10. Then Atomics.add adds 5 to this value atomically.int32[0] becomes 15.const sab = new SharedArrayBuffer(8); const uint8 = new Uint8Array(sab); uint8[0] = 255; Atomics.store(uint8, 0, 256); console.log(uint8[0]);
uint8[0] becomes 0, not 256.SharedArrayBuffer. Which code snippet correctly increments the counter without race conditions?
// Shared buffer and typed array
const sab = new SharedArrayBuffer(4);
const counter = new Int32Array(sab);
counter[0] = 0;
// Increment function
function increment() {
// Which line correctly increments?
}counter[0] with normal operators can cause race conditions when multiple threads run concurrently.Atomics.add(counter, 0, 1) safely increments the value at index 0 without conflicts.