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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With