关于Node.js中的CPU密集代码的混乱 [英] Confusion about CPU intensive code in Node.js

查看:171
本文介绍了关于Node.js中的CPU密集代码的混乱的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个新的Node.js的问题,一切并行运行,除了您的代码。这是一个很明显的人工例子,但我们想要创建一个包含函数 factorize()的数学库,其行为如下:

  var http = require('http'); 
http.createServer(function(req,res){
myMath.factorize(some_big_number,function(factors){
res.writeHead(200,{'Content-Type':'application / json'});
res.end(JSON.stringify(factors));
}
})listen(8000);
/ pre>

如何写,以便并行运行?



我有一直在查看此库中的解析代码,作为可能需要处理时间的示例。 代码的正文被认为是你的代码,还是这个并行运行?



如果没有:在编写 factorize()所以它也是非阻塞/表现像一个客户端?使用EventEmitter足够?



如果是的话:我最好的选择还是使用子进程,如这个问题



由于任何缺乏明确性,提前道歉。

解决方案

其实你不能运行它parallel(除非你使用工作模块),因为node.js中的JavaScript是在单线程中执行的,但您可以将单个线程拆分成较小的部分。例如,使用 process.nextTick ,所以当CPU正在执行代码作为较小的块而不是一个长时间运行的代码时,它的运行时间也很小。 / p>

  myLongRunningCode(callback){
do_a_piece_of_the_work();
if(ready){
callback();
} else {
//给CPU一个小休息做其他的事情
process.nextTick(function(){
//继续工作
myLongRunningCode(callback );
});
}
}


A question regarding "everything runs in parallel except your code" from someone new to Node.js. This is an obviously artificial example, but let's say I want to create a math library containing a function factorize() which behaves as follows:

var http = require('http');
http.createServer(function (req, res) {
  myMath.factorize(some_big_number,function(factors) {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify(factors));
  }
}).listen(8000);

How can this be written so that it will "run in parallel"?

I've been looking at the parsing code from this library as an example that might take some processing time. Is the body of the code considered to be "your code", or does this "run in parallel"?

If not: What do I need to do when writing factorize() so that it is also non-blocking/behaves like a client? Is using EventEmitter sufficient?

If so: Is my best option still to use child processes as suggested in this question?

Apologies in advance for any lack of clarity.

解决方案

Actually you can't run it "parallel" (unless you use a workers module) as JavaScript in node.js is executed in single thread but you can split your single thread into smaller pieces. For example with process.nextTick, so when the CPU is executing the code as smaller chunks instead of one long running code, it has small breaks to run other things as well.

myLongRunningCode(callback){
    do_a_piece_of_the_work();
    if(ready){
        callback();
    }else{
        // give the CPU a small break to do other things
        process.nextTick(function(){
            // continue working
            myLongRunningCode(callback);
        });
    }
}

这篇关于关于Node.js中的CPU密集代码的混乱的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆