Ant*_*lli 2 javascript max child-process node.js
希望我能清楚地描述我在寻找什么。使用Node和Python。
我正在尝试并行运行多个子进程(.py脚本,使用child_process.exec()),但一次不超过指定数量(例如2)。我收到的批次请求数量未知(例如,该批次有3个请求)。我想停止生成进程,直到当前进程之一完成为止。
for (var i = 0; i < requests.length; i++) {
//code that would ideally block execution for a moment
while (active_pids.length == max_threads){
console.log("Waiting for more threads...");
sleep(100)
continue
};
//code that needs to run if threads are available
active_pids.push(i);
cp.exec('python python-test.py '+ requests[i],function(err, stdout){
console.log("Data processed for: " + stdout);
active_pids.shift();
if (err != null){
console.log(err);
}
});
}
Run Code Online (Sandbox Code Playgroud)
我知道虽然循环不起作用,但这是第一次尝试。
我猜有办法做到这一点
setTimeout(someSpawningFunction(){
if (active_pids.length == max_threads){
return
} else {
//spawn process?
}
},100)
Run Code Online (Sandbox Code Playgroud)
但是我无法完全解决这个问题。
或许
waitpid(-1)
Run Code Online (Sandbox Code Playgroud)
在if语句中的for循环中,插入了while循环?但是我目前无法安装waitpid()模块。
是的,我知道在JS中阻塞执行被认为是非常糟糕的,但就我而言,我需要实现它。如果可能,我宁愿避免使用外部集群管理器类型的库。
谢谢你的帮助。
编辑/部分解决方案
一个丑陋的破解方法是使用来自以下问题的答案:这个SO问题(execSync())。但这会阻塞循环,直到最后一个孩子完成。到目前为止,这是我的计划,但并不理想。
async.timesLimit该async库中的文件是在这里使用的完美工具。它允许您异步运行一个函数n时间,但是k在任何给定时间最多并行运行这些函数调用。
async.timesLimit(requests.length, max_threads, function(i, next){
cp.exec('python python-test.py '+ requests[i], function(err, stdout){
console.log("Data processed for: " + stdout);
if (err != null){
console.log(err);
}
// this task is resolved
next(null, stdout);
});
}, function(err, stdoutArray) {
// this runs after all processes have run; what's next?
});
Run Code Online (Sandbox Code Playgroud)
或者,如果您希望致命的错误并停止循环,请致电next(err, stdout)。
| 归档时间: |
|
| 查看次数: |
1197 次 |
| 最近记录: |