[英]Run tasks in multiple threads on node.js
I need some help with node.js as i'm a newbie to it. 我需要一些node.js的帮助,因为我是新手。 I have an array of data and have to run functions with that data in multiple threads (using all CPU cores).
我有一个数据数组,必须在多个线程中使用该数据运行函数(使用所有CPU内核)。 In usual for me languages i do create threadpool with number of threads, push some tasks to it, wait until finish, send more tasks to queue.
在我常用的语言中,我确实创建了具有多个线程的线程池,将一些任务推送到它,等到完成,将更多任务发送到队列。 But i can't figure it out how to do that in nodejs.
但我无法弄清楚如何在nodejs中做到这一点。
PS: i'm using latest 0.8 branch. PS:我正在使用最新的0.8分支。
Nodejs is built to run on a single process, but you can spawn other processes. Nodejs构建为在单个进程上运行,但您可以生成其他进程。 The cluster module uses the fork method from the child_process module, but it's intended for distributing connections of a server across processes and sharing the same port.
集群模块使用child_process模块中的fork方法,但它用于跨进程分发服务器的连接并共享同一端口。
I think you want exec . 我想你想要高管 。 Example:
例:
var exec = require('child_process').exec,
child;
var array = ["a", "b", "c", "d", "e"]; // your array of data
var n = array.length; // length
var done = 0; // jobs done
var i = n; // iterator
while(i--) { // reverse while loops are faster
(function (argument) { // A closure
child = exec('node otherFunction.js '+argument, // Spawn the process, with an item from your array as an argument.
function (error, stdout, stderr) {
if (error === null) {
done += 1;
if (done === n) {
console.log('Everything is done');
}
}
});
})(array[i]);
}
The above is of course bad code and not even tested, but I think it would work. 以上当然是坏代码,甚至没有经过测试,但我认为它会起作用。 All you have to do is call the function you wanted to call on the array's items in
otherFunction.js
, inside that you would find the arguments in process.argv
. 您所要做的就是调用您想要在
otherFunction.js
的数组项目上调用的函数,在其中您将在process.argv
找到参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.