我可以使用群集模块使函数处理程序在不同的进程中发生吗?

时间:2014-08-05 19:48:39

标签: node.js multicore

我正在与一组工人建立一个“经理”流程。我想使用clusterlink)模块将工作者放入单独的进程中。由于工作人员的消息处理可能相当耗费资源,因此将其推送到不同的核心是有意义的。

这是经理的伪代码:

  for i in worker_count
    create a new process (fork = cluster.fork())       
    create a worker and pass in the process (fork) to its constructor 
    in the worker
      when the worker gets a "work" chunk 
         it should be processed on a core that is not the same as the manager  

我找不到关于群集的更多信息,而不仅仅是http.createServer等。我可以用不同的方式做到这一点,但我想知道是否有办法获取群集的“上下文”和在该上下文中放置一个函数。

1 个答案:

答案 0 :(得分:1)

当您分叉群集时,它会完全复制当前进程。有一个'主'工作者,其余的都是作为子进程创建的。将工作传递给童工的一种方法是发送消息:

if (cluster.isMaster) {
    // Spawn all your child workers here
    var worker = cluster.fork();

    // You could send a message to the worker from here if you wanted
    worker.send('some message');

    // You could loop through all the workers and send messages to them
    for (var id in cluster.workers) {
        cluster.workers[id].send('some message');
    }

} else {

    // This is where your child workers will branch into as they are not the master process
    process.on('message', function (msg) {
        if (msg === "some message") {
            doSomeStuff();
        }
    });
}