Back

Technologies:

javascriptjavascript
avatar
Tolerim
3 hours ago

The Worker thread is failing to execute code even when called in web workers.

Web workers are a useful tool for running expensive computations in the background, without interrupting the main thread and causing the UI to become unresponsive. To utilize the Astar algorithm with web workers, I created a worker class and added the following code to the main class:

const { Worker } = require("worker_threads");
const worker = new Worker("./astarA.js");
To call the worker class, I used the following code inside a method that's being called 30 times / second:

worker.postMessage({ start: s, goal: g });

worker.onmessage = function (path) {
  this.hpath = path;
  console.log("path is ", path);
};
let ls = 0;
The worker class uses the following code:

const { parentPort, workerData } = require("worker_threads");
parentPort.on("message", (message) => {
  let hpath = aStar(message.start, message.goal);
});
However, there seem to be some issues with the worker's execution time. The worker executes for only a brief period, even though the Astar algorithm has multiple loops within it. The issue is not with the algorithm, but with the thread's execution. In addition, console.log() statements in the worker class only seem to work once, and subsequent console.log() statements do not display any output.

I am using nodejs v16.17.0.

Answers(1)
avatar
Tolerim
3 hours ago
Verified Answer
It seems like you are experiencing some issues with your web worker implementation. One possible reason why the worker may be stopping prematurely could be because the parentPort.on("message", ...) event listener is not being kept alive. To ensure that the listener stays active for the duration of the worker's execution, you can wrap your Astar algorithm code inside a loop that listens for new messages from the main thread:
parentPort.on("message", (message) => {
  while (true) {  // Keep the thread listening for new messages
    let hpath = aStar(message.start, message.goal);
    parentPort.postMessage(hpath);  // Send the result back to main thread
  }
});
Regarding your issue with only being able to console.log() once in the worker class, this may be due to a buffering problem where the console output is being held until the worker finishes execution. One possible workaround is to use the console.timeStamp() function to force the console to output the log immediately:
console.log("First log message");
console.timeStamp("Log message");
console.log("Second log message");  // This should output to console
I hope this helps! Let me know if you have any further questions.
;