热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

分叉子进程并注入依赖-Forkachildprocessandinjectdependency

Icurrentlyhaveanoperationinamodulethatisblocking,soImlookingatmakingthisintoachi

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)

Then in my worker module:

然后在我的工人模块中:

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

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

如何将此示例转换为分叉的子进程?

3 个解决方案

#1


21  

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).

使用.fork()时,您正在启动一个完全独立的进程,因此您无法在父进程和子进程之间传递引用(并且仅限于创建进程后的消息传递)。

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.:

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

At top level:

在顶层:

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

In the worker process:

在工作过程中:

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

Update

更新

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):

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

At top level:

在顶层:

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'}

In worker process:

在工作过程中:

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.
    }
});

#2


0  

In the main module:

在主要模块中:

var dependency = {message: 'hello there'};
var args = [JSON.stringify(dependency)];
var child = require('child_process').fork('worker', args);
child.send('sayhello');
child.send('exit');

And in the child process module (worker.js):

并在子进程模块(worker.js)中:

var dependency = JSON.parse(process.argv[2]);
process.on('message', function(m){
    if(m == 'sayhello') console.log(dependency.message);
    else if(m == 'exit') process.exit();
});

#3


0  

a.js

a.js

var fork = require ("child_process").fork;
var child;
var init = false;

var m = module.exports = {};
m.init = function (o){
    if (init) return;
    init = true;
    child = fork (__dirname + "/child");
    child.send ({ init: o });
};
m.print = function (o){
    if (!init) return;
    child.send ({ msg: o });
};
m.uninit = function (){
    if (!init) return;
    child.on ("exit", function (){
        init = false;
    });
    child.kill ();
};

child.js

child.js

var dependency;

var print = function (o){
    console.log (o + dependency.name);
};

process.on ("message", function (o){
    if (o.init){
        dependency = o.init;
    }else{
        print (o.msg);
    }
});

b.js

b.js

var a = require ("./a");
a.init ({ name: "asd" });
a.print ("hi, ");
setTimeout (function (){
    a.uninit ();
}, 1000);

Prints: hi, asd

打印:嗨,asd


推荐阅读
  • 生成式对抗网络模型综述摘要生成式对抗网络模型(GAN)是基于深度学习的一种强大的生成模型,可以应用于计算机视觉、自然语言处理、半监督学习等重要领域。生成式对抗网络 ... [详细]
  • IhaveconfiguredanactionforaremotenotificationwhenitarrivestomyiOsapp.Iwanttwodiff ... [详细]
  • 本文介绍了C#中数据集DataSet对象的使用及相关方法详解,包括DataSet对象的概述、与数据关系对象的互联、Rows集合和Columns集合的组成,以及DataSet对象常用的方法之一——Merge方法的使用。通过本文的阅读,读者可以了解到DataSet对象在C#中的重要性和使用方法。 ... [详细]
  • 本文主要解析了Open judge C16H问题中涉及到的Magical Balls的快速幂和逆元算法,并给出了问题的解析和解决方法。详细介绍了问题的背景和规则,并给出了相应的算法解析和实现步骤。通过本文的解析,读者可以更好地理解和解决Open judge C16H问题中的Magical Balls部分。 ... [详细]
  • 知识图谱——机器大脑中的知识库
    本文介绍了知识图谱在机器大脑中的应用,以及搜索引擎在知识图谱方面的发展。以谷歌知识图谱为例,说明了知识图谱的智能化特点。通过搜索引擎用户可以获取更加智能化的答案,如搜索关键词"Marie Curie",会得到居里夫人的详细信息以及与之相关的历史人物。知识图谱的出现引起了搜索引擎行业的变革,不仅美国的微软必应,中国的百度、搜狗等搜索引擎公司也纷纷推出了自己的知识图谱。 ... [详细]
  • This article discusses the efficiency of using char str[] and char *str and whether there is any reason to prefer one over the other. It explains the difference between the two and provides an example to illustrate their usage. ... [详细]
  • 解决.net项目中未注册“microsoft.ACE.oledb.12.0”提供程序的方法
    在开发.net项目中,通过microsoft.ACE.oledb读取excel文件信息时,报错“未在本地计算机上注册“microsoft.ACE.oledb.12.0”提供程序”。本文提供了解决这个问题的方法,包括错误描述和代码示例。通过注册提供程序和修改连接字符串,可以成功读取excel文件信息。 ... [详细]
  • 本文介绍了闭包的定义和运转机制,重点解释了闭包如何能够接触外部函数的作用域中的变量。通过词法作用域的查找规则,闭包可以访问外部函数的作用域。同时还提到了闭包的作用和影响。 ... [详细]
  • 本文介绍了lua语言中闭包的特性及其在模式匹配、日期处理、编译和模块化等方面的应用。lua中的闭包是严格遵循词法定界的第一类值,函数可以作为变量自由传递,也可以作为参数传递给其他函数。这些特性使得lua语言具有极大的灵活性,为程序开发带来了便利。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 开发笔记:加密&json&StringIO模块&BytesIO模块
    篇首语:本文由编程笔记#小编为大家整理,主要介绍了加密&json&StringIO模块&BytesIO模块相关的知识,希望对你有一定的参考价值。一、加密加密 ... [详细]
  • HDU 2372 El Dorado(DP)的最长上升子序列长度求解方法
    本文介绍了解决HDU 2372 El Dorado问题的一种动态规划方法,通过循环k的方式求解最长上升子序列的长度。具体实现过程包括初始化dp数组、读取数列、计算最长上升子序列长度等步骤。 ... [详细]
  • 阿,里,云,物,联网,net,core,客户端,czgl,aliiotclient, ... [详细]
  • MongoDB用户验证auth的权限设置及角色说明
    本文介绍了MongoDB用户验证auth的权限设置,包括readAnyDatabase、readWriteAnyDatabase、userAdminAnyDatabase、dbAdminAnyDatabase、cluster相关的权限以及root权限等角色的说明和使用方法。 ... [详细]
  • 本文讨论了微软的STL容器类是否线程安全。根据MSDN的回答,STL容器类包括vector、deque、list、queue、stack、priority_queue、valarray、map、hash_map、multimap、hash_multimap、set、hash_set、multiset、hash_multiset、basic_string和bitset。对于单个对象来说,多个线程同时读取是安全的。但如果一个线程正在写入一个对象,那么所有的读写操作都需要进行同步。 ... [详细]
author-avatar
phpxiaohui
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有