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

时间:2012-08-19 09:56:56

标签: javascript multithreading node.js

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

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

1 个答案:

答案 0 :(得分:4)

Nodejs构建为在单个进程上运行,但您可以spawn其他进程。 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内找到参数。

相关问题