叉子进程和注入依赖 [英] Fork a child process and inject dependency

查看:154
本文介绍了叉子进程和注入依赖的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前在一个封锁的模块中有一个操作,所以我正在把它做成一个子进程,而不是fork。

I currently have an operation in a module that is blocking, so I'm looking at making this into a child process that I fork instead.

如果我想要做到这一点,那么我当然需要修改我的模块的架构。该模块要求通过调用模块作为函数来传递依赖关系,传递依赖关系,如下所示:

If I want to do that, then I of course need to modify the architecture of my module. The module requires that a dependency is injected by calling the module as a function, passing in the dependency, like so:

var dependency = { name: "Bob" }
require('worker')(dependency)

然后在我的 worker 模块中:

module.exports = function (dependency) {
  // Outputs { name: "Bob" }
  console.log(dependency)
}

如何将这个例子转化为一个子进程被分叉?

How can I turn this example into a child process being forked?

推荐答案

.fork()你正在旋转一个完全独立的进程,所以你不能传递父进程和子进程之间的引用(仅限于在创建进程后的消息传递)。

When using .fork() you are spinning up a completely separate process, so you are not able to pass around references between the parent and child processes (and are limited to messaging after the process has been created).

不需要消息传递的方法是在分叉进程时传递参数(在数组中)。虽然我相信你必须坚持使用简单的字符串/数字值(但是看起来这可能足够你的代码)。例如:

An approach not requiring messaging is to pass arguments (in an array) when you fork the process. Although I believe you'll have to stick with simple string/number values (but it looks like this might be enough for you from the code). Eg.:

顶级:

var name = 'bob'
var args = [name];
var childProcess = require('child_process').fork(__dirname + '/worker', args);

在工作流程中:

var name = process.argv[2]; //AFIAK elements 0 and 1 are already populated with env info

更新

如果你真的想去消息路由(如果你已经需要发送消息,我会犹豫推荐),那么你可以区分消息的类型这样的(可能会有更优雅的方式):

If you really want to go the messaging route (which I'd hesitate to recommend if you already need to send messages), then you could differentiate between the types of messages something like this (there may be more elegant ways):

在顶层:

var childProcess = require('child_process').fork(__dirname + '/worker');
childProcess.send({msgtype:'dependencies', content:dependencies});

//Then to send 'normal' message:
childProcess.send({msgtype:'myothermessagetype', content:'some content'}

在工作进程中:

process.on('message', function(msg){
    if(msg.mtype == 'dependencies') {
       var dependencies = msg.content;
       //Do something with dependencies
    } else if(msg.mtype == 'myothermessagetype') {
       var normalmessage = msg.content;
       //Do something in response to normal message.
    }
});

这篇关于叉子进程和注入依赖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆