3

I have recently encountered worker thread are a new featured implemented in nodejs, but it seems like there is no way to access and modify it from the worker thread, do you know any way to this?

const { Worker, isMainThread, parentPort } = require('worker_threads');

global.myvar = "initial variable"


if (isMainThread) {
  const worker = new Worker(__filename);
// Receive messages from the worker thread
  worker.once('message', (message) => {
    console.log(message + ' received from the worker thread!');
  });
// Send a ping message to the spawned worker thread 
  worker.postMessage("");

  setTimeout(function() {
    console.log("final variable : " + global.myvar);
  }, 2000);

} else {
  // When a ping message received, send a pong message back.
  console.log("inside worker thread");
  parentPort.on('message', (message) => {
        global.myvar = "worker variable"
  });
}

In this code I expected the final varibale to be the value "worker variable", but it show "initial variable", may I know how can I solve this?

5
  • 1
    Out of curiosity, what is it your going to use the worker thread for. Because if you don't understand how they work, there is a good chance you might not even need them. For example, I have seen some users on SO using worker threads for Async operations, and that's a total waste of resources in Node.js land. Commented Dec 8, 2020 at 16:27
  • @Keith I am getting real time stocks and crypto price data from websocket and perform some calculation which is CPU intensive, in my previous way, if i perform the calculation directly on the websocket listen function, it will just slow down the receiving and process time of subsequent websocket price feed. Do you have any better solution for this? Commented Dec 8, 2020 at 16:33
  • Yes, expensive calculations are ideal for webworkers, remember to leave the websocket bit out, just the calculations. The bit you are missing like @TJ pointed out, is you need your webworker to send a message back to the main thread, use promcess.on('message') on the main thread,.. Commented Dec 8, 2020 at 16:38
  • thank you so much for your comment, I am wondering if there will be a case where the websocket data come in very frequently, which caused my CPU will fail to handle or receive the message with latency? Because to access the data and perform in real time :) Commented Dec 8, 2020 at 16:43
  • If the data your getting from the websocket is only ever going to be consumed by the worker, they might be a benefit yes. Not because of latency processing the websocket packets, but then having to forward it to the worker. Commented Dec 8, 2020 at 17:08

1 Answer 1

9

The worker and the main thread are running in completely independent JavaScript environments. They each have their own set of globals, etc.

The worker cannot directly modify the contents of the parent's variable. It would need to send an update via a message to the parent, which the parent would process by updating the global variable.

Sign up to request clarification or add additional context in comments.

2 Comments

How can We send complex data using port messaging. i.e pupeteer browser instance.
@MuhammadUzair - I very much doubt you can, but you can use messaging (postMessage, etc.) to convey the information you need from the worker where you're using it to the main thread (or vice-versa).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.