javascript / expert
Snippet
Lock-Free Parallelism with Atomics and SharedArrayBuffer
SharedArrayBuffer allows multiple threads (Web Workers) to share the same memory space. Atomics provides static methods to perform thread-safe operations on typed arrays, preventing race conditions without the overhead of traditional mutexes.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
const buffer = new SharedArrayBuffer(1024);const uint8 = new Uint8Array(buffer);// In a Worker thread or main threadfunction safeIncrement(index) {return Atomics.add(uint8, index, 1);}// Waiting for a value change without blocking the event loopfunction waitForSignal(index, expectedValue) {const result = Atomics.wait(new Int32Array(buffer), index, expectedValue, 1000);return result === 'ok' || result === 'not-equal';}
nextjs
Breakdown
1
const buffer = new SharedArrayBuffer(1024);
Allocates a fixed-length raw binary data buffer that can be shared between workers.
2
Atomics.add(uint8, index, 1);
Atomically adds a value to the specific index, ensuring no other thread can interrupt the operation.
3
Atomics.wait(...);
Synchronously waits for a specific memory location to change, supported only in non-main threads for UI stability.