nodejs / node

Node.js JavaScript runtime ✨🐢🚀✨
https://nodejs.org
Other
107.44k stars 29.54k forks source link

Logs are not visible inside worker thread when using Atomics #40548

Open nairihar opened 3 years ago

nairihar commented 3 years ago

Version

v16.12.0

Platform

MacBook-Pro.local 20.6.0 Darwin Kernel Version 20.6.0: Wed Jun 23 00:26:31 PDT 2021; root:xnu-7195.141.2~5/RELEASE_X86_64 x86_64

Subsystem

worker_threads

What steps will reproduce the bug?

Hi,

I'm trying to work with worker_threads

I've those two files, I expect that my log Worker_1, prep for editing! should be visible in the terminal, but it's not.

I'm wondering why the first log is visible but the second not.

// main.js

const { Worker } = require('worker_threads');

const worker_1 = new Worker('./worker_1.js');

const sharedArray = new Int32Array(new SharedArrayBuffer(16));
Atomics.store(sharedArray, 0, 102);

worker_1.postMessage(sharedArray);
// worker_1.js

const { parentPort } = require('worker_threads');

parentPort.on('message', (sharedArray) => {
  console.log('Message for Worker_1 from Parent:', sharedArray);
  console.log('Worker_1, prep for editing!');
  Atomics.wait(sharedArray, 0, 102);

  Atomics.store(sharedArray, 1, 1);
  console.log('Worker_1 finished editing!', sharedArray);
});

How often does it reproduce? Is there a required condition?

always

What is the expected behavior?

I think I should see this log in terminal: Worker_1, prep for editing!

What do you see instead?

I see only the first console.log, but the second one isn't there.

Additional information

It's the same for node v14the

nairihar commented 3 years ago

This may make some sense, but what are the priorities of console.log and Atomics.wait, how do they work internally?

Screen Shot 2021-10-21 at 5 34 26 PM
theanarkh commented 1 year ago

I think because the worker is blocked and the console.log is an asynchronous API, you can use fs.writeFileSync(1, 'hello').