简体   繁体   English

NodeJS 子进程对主进程的引用

[英]NodeJS Child Process reference to main process

I'm trying to wrap my head around creating separate processes in NodeJS.我正在尝试在 NodeJS 中创建单独的进程。

If I was to fork a child process and send it an object would that object be passed in by reference?如果我要派生一个子进程并向它发送一个对象,该对象是否会通过引用传入? So if I was to edit a variable within the child process on that object it would change on the main process too?因此,如果我要在该对象的子进程中编辑一个变量,它也会在主进程上发生变化吗? Or is it the only way to do something like this is to send a message to the main process telling it what to change the variable to?或者这样做的唯一方法是向主进程发送一条消息,告诉它要将变量更改为什么?

Node.js docs clearly say that: Node.js 文档明确指出:

It is important to keep in mind that spawned Node.js child processes are independent of the parent with exception of the IPC communication channel that is established between the two.重要的是要记住,生成的 Node.js 子进程独立于父进程,但在两者之间建立的 IPC 通信通道除外。 Each process has its own memory, with their own V8 instances.每个进程都有自己的内存,有自己的 V8 实例。

But there is a concept of Shared Memory in Linux.但是Linux中有共享内存的概念。 Here is a library called 'EMS.js' that allows to use it in Node.js.这是一个名为“EMS.js”的库,允许在 Node.js 中使用它。

Here is an example.这是一个例子。 I set numbers in child and parent and then read them correspondingly.我在 child 和 parent 中设置数字,然后相应地读取它们。

master.js:大师.js:

 const {fork} = require('child_process'); const ems = require('ems')(1); const _ = require('lodash'); const shared = ems.new({ filename: '/tmp/shared.ems', heapSize: 10000, dimensions: 100, useMap: true, //Notice this option here useExisting: false, ES6proxies: true }); setInterval(function () { shared.parentProperty = `Parent sets: ${_.random(1, 100)}`; console.log(shared.childProperty); }, 500); //I inherit stdio here to see the output of both processes in console let child1 = fork('./slave-1.js', {stdio: 'inherit'});

slave-1.js: slave-1.js:

 const _ = require('lodash'); console.log('Slave started'); const ems = require('ems')(1); const shared = ems.new({ filename: '/tmp/shared.ems', dimensions: 100, useMap: true, useExisting: true, ES6proxies: true }); setInterval(function () { console.log(shared.parentProperty); shared.childProperty = `Child sets: ${_.random(1, 100)}`; }, 500);

Also check out the docs as there is a lot options + a lot of stuff like barriers etc. Plus be careful with the heap size and dimensions options not to run out of memory.还要查看文档,因为有很多选项 + 很多诸如屏障之类的东西。另外要小心堆大小和维度选项,以免内存不足。

The output:输出:

Slave started
undefined
Parent sets: 52
Child sets: 52
...

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

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