Is it possible to cut off child processes and wait for them to return to Node / JS?

I have to do a certain calculation many times. I want to split it into several cores, so I want to use child_process.fork (), and then give each child a piece of work.

This works fine, except that my main process (the one that fork () does) just continues after fork () ing and is already complete by the time the children finish their work.

What I really want to do is wait for the children to finish before continuing.

I cannot find a good way to do this in Node. Any tips?

+4
source share
1 answer

If you create a new V8 process through .fork() , it returns a new child object that implements the link layer. For instance,

 var cp = require( 'child_process' ), proc = cp.fork( '/myfile.js' ); proc.on('message', function( msg ) { // continue whatever you want here }); 

and inside /myfile.js you just send the event when you are done

 process.send({ custom: 'message' }); 

Remember that this method actually spawns a new instance of V8 that eats a good chunk of memory. Therefore, you should use this very thoughtfully. Maybe you don’t even have to do this, maybe there is a more β€œnode like” solution (using process.nextTick to calculate heavy data).

+3
source

Source: https://habr.com/ru/post/1440392/


All Articles