在node.js上的多个线程中运行任务

我需要一些node.js帮助,因为我是一个新手。 我有一个数据arrays,必须在多个线程(使用所有的CPU核心)运行与该数据的function。 通常对于我的语言,我创build了线程数量的线程池,向它推送一些任务,等待直到完成,发送更多的任务队列。 但我不知道如何在nodejs中做到这一点。

PS:我正在使用最新的0.8分支。

Nodejs是build立在一个进程上运行,但是你可以产生其他的进程。 群集模块使用来自child_process模块​​的fork方法,但它旨在跨进程分配服务器的连接并共享相同的端口。

我想你想要高pipe 。 例:

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

以上是当然不好的代码,甚至没有testing,但我认为这将工作。 所有你需要做的就是调用你想调用其他函数otherFunction.js的数组项目的otherFunction.js ,在里面你可以findprocess.argv的参数。