5

我需要一些关于 node.js 的帮助,因为我是它的新手。我有一个数据数组,并且必须在多个线程中使用该数据运行函数(使用所有 CPU 内核)。在我通常的语言中,我确实创建了具有线程数的线程池,将一些任务推送到它,等到完成,将更多任务发送到队列。但我无法弄清楚如何在nodejs中做到这一点。

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

4

1 回答 1

4

Nodejs 是为在单个进程上运行而构建的,但您可以生成其他进程。cluster模块使用来自 child_process 模块的fork方法,但它旨在跨进程分配服务器连接并共享同一端口。

我想你想要exec。例子:

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

以上当然是糟糕的代码,甚至没有经过测试,但我认为它会起作用。你所要做的就是调用你想调用的函数来调用数组中的项otherFunction.js,在里面你可以找到参数process.argv

于 2012-08-19T10:36:00.657 回答