gpt4 book ai didi

node.js - Node : will this code run multi-core or not?

转载 作者:搜寻专家 更新时间:2023-10-31 22:32:33 26 4
gpt4 key购买 nike

我将这个 Node 脚本用作我项目的“运行器”(需要同时启动/停止三个脚本)。现在我想知道从 Node 进程内部生成的 child_process 是否会使用或不会使用我的服务器将拥有的多核(我有 90% 的信心是肯定的,但安全总比遗憾好)。


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

操作系统是 Ubuntu Linux。

最佳答案

是的。 spawn() 在操作系统级别创建全新的进程。

你甚至可以使用 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);
}
});
});

(还在 exit 上添加了监听器,所以它至少会以某种方式传播错误。如果这是你想做的事情,你可能想要跟踪它们直到最后一个进程完成,然后用最大或最小的代码调用process.exit()...)

关于node.js - Node : will this code run multi-core or not?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7268215/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com