I try to get comfortable with Atomics in node.js.
For that i created a very simple test with 2 worker threads.
One that waits for a notify, and one that notfies the other.
main.js
const { Worker } = require('node:worker_threads');
const shared = new SharedArrayBuffer(4);
const sync = new Int32Array(shared);
sync[0] = 0;
new Worker('./waiter.js', { workerData: shared });
new Worker('./notifier.js', { workerData: shared });
waiter.js
const { workerData } = require('node:worker_threads');
const sync = new Int32Array(workerData);
let last = 0;
setInterval(() => {
//while (true) {
console.log('[waiter] Waiting for', last);
Atomics.wait(sync, 0, last);
last = Atomics.load(sync, 0);
console.log('[waiter] Woke up! New value:', last);
//}
}, 0);
notifier.js
const { workerData } = require('node:worker_threads');
const sync = new Int32Array(workerData);
let value = 1;
setInterval(() => {
console.log('[notifier] Stored and notifying');
Atomics.store(sync, 0, value++);
Atomics.notify(sync, 0);
}, 1000);
The problem im facing, with while(true) in the waiter, i get no output. No console.log, nothing. With setInterval it prints to stdout.
Not even with a recursive loop i get output/console.log:
const { workerData } = require('node:worker_threads');
const sync = new Int32Array(workerData);
let last = 0;
function loop() {
console.log('[waiter] Waiting for', last);
Atomics.wait(sync, 0, last);
last = Atomics.load(sync, 0);
console.log('[waiter] Woke up! New value:', last);
loop();
}
loop();
Can some one tell me why, i get no output on stdout when i use something else than setInterval?
My first guess was that while(true) block io in node.js
But then, at least the recursive function approach should work.
My first guess was that while(true) block io in node.js But then, at least the recursive function approach should work.Why do you think a recursive function would work different from a loop?process.nextTick(loop);inside the loop function.waitAsyncthough.while(true)loop never returns, and neither does the recursive function.