javascript / expert
Snippet
Shared Memory Slice Manipulation Using TypedArray Sub-slices
TypedArray sub-slices allow multiple views over a shared block of memory (SharedArrayBuffer). Mutating values atomically through one slice immediately reflects across all overlapping array views.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
import assert from 'node:assert/strict';const sharedBuffer = new SharedArrayBuffer(1024);const masterArray = new Int32Array(sharedBuffer);masterArray[0] = 42;const subView = new Int32Array(sharedBuffer, 0, 4);assert.equal(subView[0], 42);Atomics.add(subView, 0, 10);assert.equal(masterArray[0], 52);
nodejs
Breakdown
1
const sharedBuffer = new SharedArrayBuffer(1024);
Allocates a fixed-length raw binary buffer accessible across worker threads.
2
const subView = new Int32Array(sharedBuffer, 0, 4);
Creates a typed window mapping directly onto a specific offset of the underlying shared memory.
3
Atomics.add(subView, 0, 10);
Performs a thread-safe atomic addition directly operating on the shared array slice memory.