【问题标题】:How to run all functions in parallel如何并行运行所有功能
【发布时间】:2015-07-08 04:50:19
【问题描述】:

我在下面发布一段代码,它是“非异步函数”

var flag = false;
function a() {
    var a = 0;
    for (var i = 0; i < 10000000; i++) {
        a++;
    }
    console.log("first fun finished!");
    flag = true;
};

function b() {
    var a = 0;
    for (var i = 0; i < 10000000; i++) {
        a++;
    }
    console.log("second fun finished!");
};

function c() {
    var a = 0;
    for (var i = 0; i < 10000000; i++) {
        a++;
    }
    console.log(a)
};
a();
b();
console.log("This should be good");
if (flag) { //Should wait for this value before c() is called
    c();
    console.log("third fun finished!")
}

如果我们将运行上面的示例,这应该很好,c() 函数将不得不等到 a() 和 b() 函数完成工作。我期望所有函数都应该并行运行(多线程(异步)函数)。任何人都可以帮助我如何使用nodejs实现它

【问题讨论】:

  • 唯一可行的方法是通过子进程(因为它们在不同的线程中运行)
  • @KevinB 你能帮我处理任何伪问题吗?
  • 我可以做点什么,但是,我从来没有真正使用过子进程,所以最好在某个地方找到一个指南。它的要点是,您将每个单独的操作包装到它自己的“应用程序”中,然后使用节点模块(内置)生成一个进程,该进程并行运行这些应用程序,直到它们结束。
  • 这与从 node.js 执行 cmd line 命令并等待它完成本质上是一样的。 nodejs.org/api/child_process.html
  • Parallel JavaScript Code的可能重复

标签: javascript node.js multithreading timer callback


【解决方案1】:

使用Promise.allPromise.join

var Promise = require('bluebird');
return Promise.join(Promise.resolve().then(a),
                    Promise.resolve().then(b),
                    Promise.resolve().then(c),
                    function(){console.log('complete')});

【讨论】:

    【解决方案2】:

    就像在 cmets 中提到的那样,您可以使用 child_processcluster.fork。这是一个简单的child_process.spawn 实现:

    (如果您不想使用 eval,则将这些函数写在单独的文件中并调用它们)

    var spawn = require('child_process').spawn
    ...
    
    spawn('node',['-e', '('+a.toString()+')()']) // send the function as string and evaluate in node
      .stdout.on('data', console.log.bind(console))
      .on('close',function(){
        //call c() when a() ended
        c()
      })
      .setEncoding('utf8')
    
    spawn('node',['-e', '('+b.toString()+')()'])
      .stdout.on('data', console.log.bind(console))
      .setEncoding('utf8')
    

    【讨论】:

      猜你喜欢
      • 2018-09-16
      • 1970-01-01
      • 1970-01-01
      • 2017-02-15
      • 1970-01-01
      • 2021-06-26
      • 1970-01-01
      • 1970-01-01
      • 2020-06-28
      相关资源
      最近更新 更多