javascript / expert
Snippet
Lock-free Concurrency with Atomics
When sharing memory between Node.js worker threads via SharedArrayBuffer, you must avoid race conditions. The Atomics API provides low-level, thread-safe operations like load, store, and wait/notify, allowing for high-performance, lock-free communication between threads.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
const buffer = new SharedArrayBuffer(1024);const view = new Int32Array(buffer);// In Worker A:Atomics.store(view, 0, 100);Atomics.notify(view, 0, 1);// In Worker B:Atomics.wait(view, 0, 0); // Wait until index 0 is not 0const val = Atomics.load(view, 0);console.log(`Received: ${val}`);
nodejs
Breakdown
1
Atomics.store(view, 0, 100)
Performs an atomic write operation, ensuring the value is visible to all threads immediately without cache inconsistencies.
2
Atomics.wait(view, 0, 0)
Causes the thread to sleep until a specific memory location changes, provided the current value matches the expected one.