Confusion about CPU intensive code in Node.js

对着背影说爱祢 提交于 2019-12-02 19:26:05

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

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!