javascript / expert
Snippet
Atomic Wait-Notify for Low-Latency Thread Sync
Atomics.wait() and Atomics.notify() allow for efficient, low-level synchronization between Worker Threads sharing memory. Unlike postMessage, this mechanism provides a way to pause a thread until a specific condition in a SharedArrayBuffer is met, minimizing CPU cycles spent on busy-waiting.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const { Worker, isMainThread, workerData } = require('worker_threads');if (isMainThread) {const sab = new SharedArrayBuffer(4);const int32 = new Int32Array(sab);new Worker(__filename, { workerData: sab });console.log('Main: Waiting...');Atomics.wait(int32, 0, 0);console.log('Main: Notified!');} else {const int32 = new Int32Array(workerData);setTimeout(() => {Atomics.store(int32, 0, 1);Atomics.notify(int32, 0, 1);}, 1000);}
nodejs
Breakdown
1
Atomics.wait(int32, 0, 0);
Sleeps the thread if the value at index 0 is currently 0.
2
Atomics.notify(int32, 0, 1);
Wakes up one thread that is waiting on index 0 of the shared buffer.