开发者

NodeJS: will this code run multi-core or not?

I'm using this node script as a "runner" for my project (need to start/stop three scripts at the same time). Now I wonder if the child_process's spawn from inside a node process will or won't use multi cores that my server would have (I'm 90% confident on a YES, but better safe than sorry).


    var CP = require("child_process")
      , children = [ 'server1', 'server2', 'server3' ]
     开发者_如何学编程 , child

    children.forEach(function(name) {

      child = CP.spawn("node", [name] )

      child.stdout.on('data', function (data) {
        process.stdout.write(data.toString());
      })

      child.stderr.on('data', function (data) {
        process.stdout.write(data.toString());
      })
    }
  });

OS is Ubuntu Linux.


Yup. spawn() creates completely new processes on the OS-level.

And you could even simplify it a bit by using pipe():

var spawn = require("child_process").spawn
  , children = [ 'server1', 'server2', 'server3' ]
  , child

children.forEach(function(name) {
  child = spawn("node", [name] )

  child.stdout.pipe(process.stdout);
  child.stderr.pipe(process.stderr);

  // Catch errors (dies quite hard on first child with non-zero exit code...)
  child.on('exit', function (code) {
    if(code !== 0) {
      process.exit(code);
    }
  });
});

(Also added listener on exit, so it'll at least propagate errors in some way. If it's something you want to do, you may want to keep track of them until the last process has finished, and then call process.exit() with the largest or smallest code...)


This will absolutely utilize multiple cores. Node won't, and never should, bind a child process to a specific CPU or CPU core.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜