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?
promcess.on('message')on the main thread,..