Creating and Sharing a SharedArrayBuffer
You'll learn how to instantiate a SharedArrayBuffer and send it to multiple workers, enabling true shared memory concurrency.
The Core Idea
A SharedArrayBuffer acts like a shared whiteboard that multiple workers can read from and write to simultaneously. Unlike typical postMessage data (which gets copied), a SharedArrayBuffer is literally the same memory viewed by all participants. You create it in one context, then transfer a reference to workers via postMessage.
Creating a SharedArrayBuffer
Instantiate a SharedArrayBuffer by specifying its byte size:
// Main thread
const sharedBuffer = new SharedArrayBuffer(1024); // 1024 bytes
This allocates 1KB of memory that can be shared across threads.
Sharing It With Workers
To share the buffer, send it through postMessage:
// Main thread
const worker = new Worker('worker.js');
worker.postMessage({ buffer: sharedBuffer });
The worker receives a reference to the same memory:
// worker.js
self.addEventListener('message', (event) => {
const { buffer } = event.data;
const view = new Int32Array(buffer); // Access the shared memory
view[0] = 42; // Write directly to shared memory
});
Sharing With Multiple Workers
Send the same buffer to multiple workers:
const worker1 = new Worker('worker1.js');
const worker2 = new Worker('worker2.js');
worker1.postMessage({ buffer: sharedBuffer });
worker2.postMessage({ buffer: sharedBuffer });
// Both workers now share the same memory!
Changes from worker1 are immediately visible to worker2 without additional messaging.
The Analogy
Think of regular postMessage as sending photocopies—each recipient gets their own independent copy. SharedArrayBuffer is like giving everyone a key to the same room; changes made by anyone are instantly visible to everyone else.
Key Takeaway: Create a SharedArrayBuffer with new SharedArrayBuffer(byteLength), then share it across workers via postMessage—all recipients access the same underlying memory, not copies.