Reputation: 2069
I'm trying to wrap my head around creating separate processes in 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?
Upvotes: 1
Views: 744
Reputation: 4326
Node.js docs clearly say that:
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. Each process has its own memory, with their own V8 instances.
But there is a concept of Shared Memory in Linux. Here is a library called 'EMS.js' that allows to use it in Node.js.
Here is an example. I set numbers in child and parent and then read them correspondingly.
master.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:
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
...
Upvotes: 1