capypad
0 day streak
javascript / expert
Snippet

Thread-Safe Synchronization with Atomics

Atomics provides static methods for performing atomic operations on SharedArrayBuffer data. This is crucial for multi-threaded JavaScript (Web Workers) to prevent race conditions and synchronize memory access between threads.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
const buffer = new SharedArrayBuffer(1024);
const i32 = new Int32Array(buffer);
 
// In Worker A
Atomics.store(i32, 0, 123);
Atomics.notify(i32, 0, 1);
 
// In Worker B
const result = Atomics.wait(i32, 0, 0);
if (result === 'ok') {
console.log(Atomics.load(i32, 0));
}
Breakdown
1
SharedArrayBuffer
A memory buffer that can be shared across multiple threads/workers.
2
Atomics.wait(i32, 0, 0)
Pauses execution if the value at index 0 is 0, until notified.
3
Atomics.notify(i32, 0, 1)
Wakes up one worker waiting on index 0 of the array.