Sub topic 4
Reading and Writing Shared Memory Through Typed Arrays
A SharedArrayBuffer is a block of raw bytes. It has no indexing operator and no notion of integers or floats, so you cannot read or write it directly. You always reach its contents through a view. A view is either a typed array such as Int32Array or a DataView. This chapter covers how views map onto shared bytes, how to lay out several kinds of data in one buffer, and the alignment, endianness, and copying rules that cause most early bugs.
This chapter assumes you already know ES2015+ syntax and the basics of ArrayBuffer and typed arrays on ordinary, non-shared memory. It also assumes you have created a SharedArrayBuffer and posted it to a worker, as shown in the previous chapters. The examples run in Node.js, which exposes SharedArrayBuffer without any extra setup. In a browser, the page must be cross-origin isolated first.
Views are windows, not copies
When you construct a typed array over a SharedArrayBuffer, no data is copied. The view records three things: the buffer, a starting byte offset, and a length in elements. Every read or write through the view goes straight to the shared bytes. This means every thread holding a view on the same buffer can observe the change.
You can create as many views on one buffer as you like, and they can overlap. A write through one view is visible through every other view that covers the same bytes.
Laying out a buffer with several views
Real programs often need mixed data in one buffer. A common case is a few integer control fields followed by a block of payload. You plan the layout in bytes, then create one view per region.
const HEADER_SLOTS = 2; // [0] = count, [1] = status
const HEADER_BYTES = HEADER_SLOTS * Int32Array.BYTES_PER_ELEMENT; // 8
const SAMPLE_COUNT = 4;
const TOTAL_BYTES = HEADER_BYTES + SAMPLE_COUNT * Float64Array.BYTES_PER_ELEMENT; // 40
const sab = new SharedArrayBuffer(TOTAL_BYTES);
const header = new Int32Array(sab, 0, HEADER_SLOTS);
const samples = new Float64Array(sab, HEADER_BYTES, SAMPLE_COUNT);
samples[0] = 3.14;
header[0] = 1;
console.log(header.byteOffset, header.byteLength); // 0 8
console.log(samples.byteOffset, samples.byteLength); // 8 32
console.log(sab.byteLength); // 40To share this layout with a worker, you post either the buffer or the views themselves. When you post a typed array whose buffer is shared, the receiver gets a new view object with the same offset and length, and that view points at the same shared bytes. The view object is cloned. The memory is not.
Alignment and length rules
The typed array constructor enforces two rules when you pass a byte offset:
- The
byteOffsetmust be a multiple of the element size. Use multiples of 4 forInt32Arrayand multiples of 8 forFloat64ArrayandBigInt64Array. - If you omit the length, the bytes remaining after the offset must divide evenly by the element size.
If you break either rule, the constructor throws a RangeError immediately.
const sab = new SharedArrayBuffer(10);
try {
new Int32Array(sab, 2); // offset 2 is not a multiple of 4
} catch (e) {
console.log(e.constructor.name); // RangeError
}
try {
new Int32Array(sab); // 10 bytes is not a multiple of 4
} catch (e) {
console.log(e.constructor.name); // RangeError
}
const ok = new Int32Array(sab, 4, 1); // offset 4, one element: bytes 4-7
console.log(ok.length); // 1Put the regions with the largest elements first, or pad each region up to the next multiple of 8. Then every view starts on a legal boundary. In the header example, the 8-byte header leaves the Float64Array correctly aligned at offset 8. A 4-byte header would break it.
Element types and what Atomics accepts
Plain indexing works on every typed array over shared memory. The Atomics methods, covered in later chapters, accept only integer views. Choose your view types with that in mind, because you cannot switch types later without changing the layout.
| View type | Bytes per element | Plain read/write | Atomics read-modify-write | Atomics.wait / notify |
|---|---|---|---|---|
| Int8Array, Uint8Array | 1 | Yes | Yes | No |
| Int16Array, Uint16Array | 2 | Yes | Yes | No |
| Int32Array | 4 | Yes | Yes | Yes |
| Uint32Array | 4 | Yes | Yes | No |
| BigInt64Array | 8 | Yes | Yes | Yes |
| BigUint64Array | 8 | Yes | Yes | No |
| Uint8ClampedArray | 1 | Yes | No | No |
| Float32Array, Float64Array | 4, 8 | Yes | No | No |
| DataView | any | Yes | No | No |
Two consequences follow from this table. First, control fields such as flags, counters, and indexes should live in an Int32Array (or BigInt64Array) so that you can wait on them. Second, floating-point payloads cannot be updated atomically. You protect them with a lock or a flag-based handoff. Another option is to store their bit patterns in a BigInt64Array.
BigInt64Array and BigUint64Array take BigInt values only. Assigning a plain number throws.
const big = new BigInt64Array(new SharedArrayBuffer(8));
big[0] = 5n;
console.log(big[0]); // 5n
try {
big[0] = 5;
} catch (e) {
console.log(e.constructor.name); // TypeError
}Overlapping views and byte order
Because views can overlap, you can inspect the same bytes as different types. This is useful for debugging and for serialization. It also exposes byte order. Typed arrays use the platform's native endianness, and almost every current CPU is little-endian.
const sab = new SharedArrayBuffer(4);
const asInt = new Int32Array(sab);
const asBytes = new Uint8Array(sab);
asInt[0] = 0x01020304;
console.log([...asBytes]); // [4, 3, 2, 1] on little-endian hardware
asBytes[0] = 0xff;
console.log(asInt[0].toString(16)); // 10203ffWhen the byte order must be fixed, use a DataView. Typical cases are file formats, network protocols, or data shared with WebAssembly modules that assume a specific encoding. A DataView takes an explicit littleEndian argument on each call and has no alignment requirement. The trade-off is that Atomics cannot operate on it.
const sab = new SharedArrayBuffer(4);
const dv = new DataView(sab);
dv.setUint16(1, 0x1234, false); // big-endian, at an odd offset
console.log([...new Uint8Array(sab)]); // [0, 18, 52, 0]
console.log(dv.getUint16(1, true).toString(16)); // 3412subarray shares, slice copies
Typed arrays have two methods that look alike but behave very differently on shared memory:
subarray(begin, end)returns a new view on the same buffer. Writes through it are shared.slice(begin, end)copies the elements into a new, ordinaryArrayBuffer. The result is private to the calling thread.
SharedArrayBuffer.prototype.slice also copies. It returns a new, separate SharedArrayBuffer, so other threads holding the original buffer will not see writes to the copy.
const data = new Int32Array(new SharedArrayBuffer(16));
const window = data.subarray(1, 3);
window[0] = 7;
console.log(data[1]); // 7
console.log(window.buffer === data.buffer); // true
const copy = data.slice(1, 3);
copy[0] = 99;
console.log(data[1]); // 7
console.log(copy.buffer instanceof SharedArrayBuffer); // false
const sabCopy = data.buffer.slice(0);
console.log(sabCopy instanceof SharedArrayBuffer, sabCopy === data.buffer); // true falseThe same caution applies to helpers that create arrays. Array.from(view), the spread operator, map, and filter all produce private copies. Use them for snapshots, and keep in mind that a snapshot taken without synchronization may mix values from before and after another thread's write.
Detecting whether a view is shared
Library code sometimes receives a typed array without knowing what backs it. Check the buffer:
function isShared(view) {
return typeof SharedArrayBuffer !== 'undefined' &&
view.buffer instanceof SharedArrayBuffer;
}
console.log(isShared(new Int32Array(4))); // false
console.log(isShared(new Int32Array(new SharedArrayBuffer(16)))); // trueThe typeof guard matters in browsers. On pages that are not cross-origin isolated, the SharedArrayBuffer global may be missing, and a bare instanceof against it throws a ReferenceError.
Common errors
- Misaligned offsets. The constructor throws a
RangeError. Pad regions to the largest element size. - Float control fields. Flags stored in a
Float64Arraycannot be passed toAtomics.waitor updated atomically. Move them to anInt32Array. - Using
slicewhen you meantsubarray. The other thread never sees your writes. Checkview.buffer === original.buffer. - Assuming endianness in a protocol. Overlapping typed arrays follow the host's byte order. Use a
DataViewwith an explicit flag for external formats. - Mismatched layouts. The two threads build views with different offsets and silently read the wrong bytes. Share the layout constants.
Exercise
You need a shared buffer holding one Int32 status flag that a worker will Atomics.wait on, followed by three Float64 coordinates. You write const sab = new SharedArrayBuffer(28); const flag = new Int32Array(sab, 0, 1); const coords = new Float64Array(sab, 4, 3);. What happens, and how do you fix the layout?
Show answer
The Float64Array constructor throws a RangeError because byte offset 4 is not a multiple of 8. Pad the header to 8 bytes: allocate 8 + 3 * 8 = 32 bytes, keep the flag at offset 0 as new Int32Array(sab, 0, 1), and create the coordinates as new Float64Array(sab, 8, 3). Alternatively, put the Float64 region first at offset 0 and the Int32 flag at offset 24.
Exercise
A worker receives shared, an Int32Array over a SharedArrayBuffer. It runs const part = shared.slice(0, 4); part[0] = 1; and the main thread never sees the change. Why, and what single change fixes it?
Show answer
TypedArray.prototype.slice copies the elements into a new, non-shared ArrayBuffer, so part[0] = 1 writes to private memory. Use shared.subarray(0, 4) instead, which returns a view on the same shared buffer.
Exercise
On a little-endian machine, const sab = new SharedArrayBuffer(4); new Uint8Array(sab).set([0x78, 0x56, 0x34, 0x12]); runs. What do new Int32Array(sab)[0].toString(16) and new DataView(sab).getInt32(0, false).toString(16) print?
Show answer
The Int32Array uses native little-endian order and prints 12345678. The DataView call reads big-endian because littleEndian is false, and prints 78563412.