Reputation: 531
I am using cluster (node js ) and I want every worker use the first element of an array, I want to use this method because I don't want to use a for loop
Multi_processing = (() => {
let name;
x = [1,2,3,4]
return async() => {
if (cluster.isMaster) {
// name = await prompt(' input ');// input which I want to be reused in else
console.log(`Master ${process.pid} is running`);
for (let i = 0; i <2; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} finished`);
});
} else {
console.log(x.shift()) // name is undefined
console.log(`Worker ${process.pid} started`);
console.log(x)
}
};
})();
Multi_processing();
So I did it in that way so the first worker that start use the first element then delete it and so on.
Upvotes: 0
Views: 143
Reputation: 16449
You are creating separate processes with separate memory. The array is copied into each process. The easiest way to achieve what you want is to pass the values to each process:
const cluster = require('cluster');
Multi_processing = (() => {
return async () => {
if (cluster.isMaster) {
x = [1, 2, 3, 4];
console.log(`Master ${process.pid} is running`);
for (let i = 0; i < 2; i++) {
cluster.fork({ x: x[i] });
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} finished`);
});
} else {
console.log(`Worker ${process.pid} started`);
console.log(process.env.x);
}
};
})();
Multi_processing();
Another way is implement inter-process communication (IPC) and let the workers and master communicate. Here you can find more about IPC in Node.js.
Upvotes: 2