我正在与一组工人建立一个“经理”流程。我想使用cluster
(link)模块将工作者放入单独的进程中。由于工作人员的消息处理可能相当耗费资源,因此将其推送到不同的核心是有意义的。
这是经理的伪代码:
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
等。我可以用不同的方式做到这一点,但我想知道是否有办法获取群集的“上下文”和在该上下文中放置一个函数。
答案 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();
}
});
}