[英]How do I make each worker use the first element of an list in Node.JS?
我正在使用集群(節點 js),我希望每個工作人員都使用數組的第一個元素,我想使用這種方法,因為我不想使用 for 循環
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();
所以我這樣做了,所以第一個開始使用第一個元素的工人然后刪除它等等。
您正在使用單獨的 memory 創建單獨的進程。 該數組被復制到每個進程中。 實現您想要的最簡單的方法是將值傳遞給每個進程:
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();
另一種方式是實現進程間通信(IPC),讓worker和master進行通信。 在這里您可以找到有關 Node.js 中 IPC 的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.