Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modify global variable from worker thread in nodejs

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?

like image 643
dramasea Avatar asked May 25 '26 04:05

dramasea


1 Answers

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.

like image 82
T.J. Crowder Avatar answered May 27 '26 17:05

T.J. Crowder