Home > Net >  Loop inside worker thread is not working in nodejs
Loop inside worker thread is not working in nodejs

Time:12-08

I have the following code.

if (isMainThread) {
  let worker = new Worker(__filename, {
    workerData: "thread-1",
  });
  worker.on("message", (data) => {
    console.log("Got message from worker : ", data);
  });

  worker.on("error", (err) => {
    console.log("error", err);
  });

  worker.on("exit", (code) => {
    if (code !== 0)
      console.log(new Error(`Worker stopped with exit code ${code}`));
  });
} else {
  while (true) console.log(workerData);
}

The above code prints thread-1 for only one time. Ideally, it should print continuously.

When I replace

while (true) console.log(workerData);
// with
for (let i = 0; i < 5; i  ) console.log(workerData);

Then thread-1 is being logged for 5 times.

Also when I keep while loop after for loop, then it is login thread-1 for only one time.

  for (let i = 0; i < 5; i  ) console.log(workerData);
  while (true) console.log(workerData);

The above code prints thread-1 for only one time.

CodePudding user response:

So, node.js in general does not work well if you don't give the event loop some cycles to process events.

And, doing an infinite loop like this:

while (true) console.log(workerData);

Never gives the event loop any cycles. In your example, this shows up in your worker threads because console.log() in a workerThread messages the logging to the main thread and the main thread has to be able to receive that message in order to actually log it to the console. To manage concurrency with console.log(), nodejs sends all logging to the main thread via the interprocess messaging and that messaging has to be getting processed promptly for logging from a workerThread to show up promply. If either the workerThread or the main thread is stuck in an infinite loop, not processing event loop messages, then you will not necessarily get all the console.log() messages you are expecting, particularly from the WorkerThread.

The moral of the story here is that things will only work as expected when you are regularly allowing the event loop to process messages. This is not only true for the main thread, but also for the workerThread. If you're infinite looping anywhere, that will cause some things not to work as expected. For workerThreads, this will include anything that tries to communicate with the main thread.

  • Related