Node.js 中 CPU 密集型代码的困惑

发布于 2024-11-02 14:23:51 字数 1005 浏览 1 评论 0 原文

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

如何编写它才能“并行运行”?

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

如果不是:在编写 factorize() 时我需要做什么,以便它也是非阻塞/行为像客户端?使用EventEmitter就足够了吗?

如果是这样:我的最佳选择仍然是按照 子进程 https://stackoverflow.com/questions/3491811/node-js-and-cpu-intense-requests">这个问题?

对于任何不明确之处提前致歉。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

╭ゆ眷念 2024-11-09 14:23:51

实际上你不能“并行”运行它(除非你使用 workers 模块)作为 JavaScript Node.js 在单线程中执行,但您可以将单线程拆分为更小的部分。例如,使用 process.nextTick 时,当 CPU 将代码作为较小的块而不是长时间运行的代码执行时,它也会有小的中断来运行其他事情。

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

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);
        });
    }
}
恍梦境° 2024-11-09 14:23:51

要编写非阻塞代码,您必须进行消息传递。

要进行消息传递,您必须打开一个流并通过它传递消息。这涉及与其他进程对话或与子进程对话。

您可以创建子进程来为您在节点中执行繁重的工作,或者您可以创建一个 tcp/web 服务来为您执行繁重的工作。只需让节点将消息传递给它们,然后当外部进程完成繁重的工作时,将数据发送到您的响应中。

To write non blocking code you have to do message passing.

To do message passing you have to open a stream and pass messages through it. This involves talking to some other process or talking to a sub process.

You can create child processes to do heavy lifting for you in node or you can create a tcp/web service to do heavy lifting for you. Just get node to pass messages to them and then send data down your response when the external processes have done the heavy lifting.

暮年慕年 2024-11-09 14:23:51

你的所有 JS 代码不能并行运行。永远不会同时执行多个函数。
CPU 密集型代码将使您的程序无法执行其他操作,直到该代码结束。

我建议您使用 setTimeout 拆分代码或在单独的进程中完成您的工作。但这一定是非常密集的代码;)

all your JS code can NOT run in parallel. There are never multiple functions executed at the same time.
CPU intensive code would make your program unable to do something else until this code ends.

I recommend you to split your code with setTimeout or do your job in a separate process. But this must be REALLY intensive code ;)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文