Atomics Update Shared Int32Array Cells

Mutate Int32Array cells across a SharedArrayBuffer with Atomics add, store, compareExchange, and sub, where every operation reports the observed previous value.

JavascriptData Integrity

Code

javascriptsnippet
18 lines
// SharedArrayBuffer 上的 Int32Array:跨线程共享同一块内存
const shared = new SharedArrayBuffer(16);
const cells = new Int32Array(shared);

// add 原子累加,返回旧值:并发线程调用也不会丢更新
console.log('add  : old=' + Atomics.add(cells, 0, 5) + ' now=' + Atomics.load(cells, 0));
console.log('add  : old=' + Atomics.add(cells, 0, 2) + ' now=' + Atomics.load(cells, 0));

// store 覆盖写入,load 读取
Atomics.store(cells, 1, 100);
console.log('store:', Atomics.load(cells, 1));

// compareExchange:仅在当前值符合预期时写入,返回实际旧值
console.log('cas hit :', Atomics.compareExchange(cells, 1, 100, 150), '->', Atomics.load(cells, 1));
console.log('cas miss:', Atomics.compareExchange(cells, 1, 100, 999), '->', Atomics.load(cells, 1));

// sub 原子递减,可以为负
console.log('sub  : old=' + Atomics.sub(cells, 0, 3) + ' now=' + Atomics.load(cells, 0));

Output

Captured from a sandboxed run of this snippet in the build pipeline.

add  : old=0 now=5
add  : old=5 now=7
store: 100
cas hit : 100 -> 150
cas miss: 150 -> 150
sub  : old=7 now=4

Inside the snippet

Module-level bindings hold the data — shared, cells — with no function scope in between.

Putting it to use

Running the file prints labeled results such as add : old=, store:, cas hit : — each operation’s effect is visible in the output.

Core lines

const shared = new SharedArrayBuffer(16);
const cells = new Int32Array(shared);
Atomics.store(cells, 1, 100);

Interactive Tools for This Topic

FAQ

Is a package install part of the setup?
No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `shared`, `cells`.