简体   繁体   English

如何让每个工作人员使用 Node.JS 中列表的第一个元素?

[英]How do I make each worker use the first element of an list in Node.JS?

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我正在使用集群(节点 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();

So I did it in that way so the first worker that start use the first element then delete it and so on.所以我这样做了,所以第一个开始使用第一个元素的工人然后删除它等等。

You are creating separate processes with separate memory.您正在使用单独的 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.另一种方式是实现进程间通信(IPC),让worker和master进行通信。 Here you can find more about IPC in Node.js. 在这里您可以找到有关 Node.js 中 IPC 的更多信息。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM