javascript / expert
Snippet
Thread-Safe Concurrency with Atomics
Atomics provide low-level synchronization primitives for SharedArrayBuffer. Unlike standard arithmetic, Atomics ensure that operations are completed without interruption by other threads, preventing data corruption in multi-threaded Node.js applications.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
const buffer = new SharedArrayBuffer(1024);const view = new Int32Array(buffer);// In a worker or main thread:function incrementCounter(index) {// Atomic addition ensures no race conditions across threadsreturn Atomics.add(view, index, 1);}function waitForUpdate(index, expectedValue) {// Suspends execution until the value at index changesAtomics.wait(view, index, expectedValue);console.log('Value updated!');}
nodejs
Breakdown
1
new SharedArrayBuffer(1024)
Creates a memory segment that can be shared between the main thread and workers.
2
Atomics.add(view, index, 1)
Performs a thread-safe addition, returning the old value before the increment.
3
Atomics.wait(view, index, expectedValue)
Efficiently puts a thread to sleep until notified or the value changes from the expected one.