怎样的NodeJS创建非阻塞计算 [英] NodeJs how to create a non-blocking computation

查看:202
本文介绍了怎样的NodeJS创建非阻塞计算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图让我的头周围创造一个的NodeJS非阻塞一块重计算。就拿这个例子(剥离出来的其他的东西):

I am trying to get my head around creating a non-blocking piece of heavy computation in nodejs. Take this example (stripped out of other stuff):

http.createServer(function(req, res) {
    console.log(req.url);
    sleep(10000);
    res.end('Hello World');
}).listen(8080, function() { console.log("ready"); });

你可以想像,如果我同时打开2浏览器窗口时,首先会等待10秒,其它将等待20,符合市场预期。所以,手持知识,回调是某种异步I去除睡眠,并把这个代替:

As you can imagine, if I open 2 browser windows at the same time, the first will wait 10 seconds and the other will wait 20, as expected. So, armed with the knowledge that a callback is somehow asynchronous I removed the sleep and put this instead:

doHeavyStuff(function() {
    res.end('Hello World');
});

与功能简单的定义:

with the function simply defined:

function doHeavyStuff(callback) {
    sleep(10000);
    callback();
}

这当然不行......我也试图定义一个EventEmitter并注册,但发射器的主要功能有睡眠里面发光完成,例如,所以一切再次运行之前块。

that of course does not work... I have also tried to define an EventEmitter and register to it, but the main function of the Emitter has the sleep inside before emitting 'done', for example, so again everything will run block.

我想知道这里别人怎么写非阻塞code ...例如mongojs模块或child_process.exec是无阻塞的,这意味着,在code要么他们叉某处在另一个线程和进程侦听其事件。我怎样才能在梅托德复制这一点,例如有一个漫长的过程去?

I am wondering here how other people wrote non-blocking code... for example the mongojs module, or the child_process.exec are non blocking, which means that somewhere down in the code either they fork a process on another thread and listen to its events. How can I replicate this in a metod that for example has a long process going?

我是不是完全误解了范式的NodeJS? :/

Am I completely misunderstanding the nodejs paradigm? :/

谢谢!

感谢您的回答给Linus,的确是唯一的办法就是生成一个子进程,例如像另一个节点脚本:

Thanks for the answer to Linus, indeed the only way is to spawn a child process, like for example another node script:

http.createServer(function(req, res) {
    console.log(req.url);

    var child = exec('node calculate.js', function (err, strout, strerr) {
        console.log("fatto");
        res.end(strout);
    });

}).listen(8080, function() { console.log("ready"); });

该calculate.js可以对自己的时间去做它需要返回。以这种方式,多个请求将并行运行可以这么说。

The calculate.js can take its time to do what it needs and return. In this way, multiple requests will be run in parallel so to speak.

推荐答案

您不能这样做,直接,不使用一些节点的IO模块(如 FS )。如果你需要做一个长期运行的计算,我建议你做,在一个子进程(例如 child_process.fork )或队列中。

You can't do that directly, without using some of the IO modules in node (such as fs or net). If you need to do a long-running computation, I suggest you do that in a child process (e.g. child_process.fork) or with a queue.

这篇关于怎样的NodeJS创建非阻塞计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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