Sub topic 2
Creating and Sharing a SharedArrayBuffer
This chapter assumes you know ES2015+ syntax, ArrayBuffer and typed arrays such as Int32Array, and how to start a Web Worker and exchange messages with postMessage.
ArrayBuffer Versus SharedArrayBuffer
A SharedArrayBuffer is a fixed-length block of raw binary memory, like an ArrayBuffer. The difference shows up when you send it to another agent, such as a worker. An ArrayBuffer passed to postMessage is either copied through structured cloning, or transferred, which detaches it from the sender. A SharedArrayBuffer is never copied or detached. The receiver gets a new SharedArrayBuffer object that points at the same underlying bytes.
| Behavior with `postMessage` | `ArrayBuffer` | `SharedArrayBuffer` |
|---|---|---|
| Default | Bytes are copied | Memory is shared |
| In the transfer list | Ownership moves and the sender's buffer is detached | Throws `DataCloneError` |
| Sender can still use it | Yes after a copy, no after a transfer | Yes |
| Later writes visible to the other side | No | Yes |
Creating a Buffer
The constructor takes a length in bytes. The memory starts zero-filled, and the length cannot change. A later chapter covers growable buffers.
const sab = new SharedArrayBuffer(16);
console.log(sab.byteLength); // 16
console.log(new Int32Array(sab)[0]); // 0You never read the bytes directly. You wrap them in a typed array view, and every view on the same buffer, in any thread, sees the same bytes.
Sharing with a Worker
Post the buffer itself, then build a view on each side. Here the worker writes a value and the main thread reads it from its own view:
// main.js
const sab = new SharedArrayBuffer(16);
const shared = new Int32Array(sab);
const worker = new Worker('worker.js');
worker.postMessage(sab);
worker.onmessage = () => {
console.log(Atomics.load(shared, 0)); // 42
};
// worker.js
self.onmessage = (event) => {
const shared = new Int32Array(event.data);
Atomics.store(shared, 0, 42);
self.postMessage('done');
};The message 'done' carries no data. It only tells the main thread to look. The value 42 arrived through the shared memory. Atomics.load and Atomics.store make the access safe across threads, and later chapters explain why they are needed.
Common Errors
- Putting the buffer in the transfer list.
worker.postMessage(sab, [sab])throwsDataCloneError, because shared memory cannot change owners. Post it without a transfer list. SharedArrayBuffer is not definedin a browser. Browsers expose the constructor only on cross-origin isolated pages. The next chapter shows the headers that enable it.- Posting a view instead of the buffer. Posting an
Int32Arrayover shared memory works, since the receiver gets a view on the same memory. Posting a view over a plainArrayBuffercopies the data. Check which buffer is underneath. - Expecting a copy. Code that changes a buffer after posting it, on the assumption that the receiver kept a snapshot, will see those changes show up on the other side.
Exercise
The main thread runs const ab = new ArrayBuffer(8); worker.postMessage(ab, [ab]); console.log(ab.byteLength); and then repeats the code with new SharedArrayBuffer(8). What happens in each case?
Show answer
With the ArrayBuffer, the transfer detaches the buffer and the log prints 0. With the SharedArrayBuffer, postMessage throws a DataCloneError because shared memory cannot appear in a transfer list. Removing the transfer list fixes it, and byteLength stays 8.
Exercise
A worker receives a SharedArrayBuffer and writes 7 into index 0 of an Int32Array over it. The main thread had posted a copy of a plain ArrayBuffer instead. Which value does the main thread's view show at index 0, and why?
Show answer
It shows the original value, 0 for a new buffer. A plain ArrayBuffer is structured-cloned, so the worker wrote into its own separate copy. Only a SharedArrayBuffer would make the write visible to the main thread.