如何在nodejs中添加数以百万计的数字而不会阻塞进一步的执行?
我正试图在节点js中实现一个问题的解决scheme,即:
例如:
Ur是: http:// localhost / sum / 5
应该返回
“从1到5的数字之和是:15”
如果
url: http:// localhost / sum / 100
答案应该是:
“从1到100的数字总和是:4950”
参数可以是巨大的:
例如:
url: http:// localhost / sum / 100000000 (千万)
在任何时候,服务器都不应该只处理一个请求。
我读了某处setImmediate可能会有所帮助。
1 + 2 + 3 + … + n的总和可以用n(n + 1)/ 2表示。参见这个链接了解更多信息。
一般来说,当你想要非阻塞执行,你可以使用child_process模块: https ://nodejs.org/api/child_process.html
一个例子看起来像这样:
//fork a new process var cp = require('child_process'); var child = cp.fork('./intensiveTask.js',[],{}); //listen for messages from the child process child.on('message', function(ret) { console.log("child process has finished", ret.data); //kill the child process child.kill(); }); //send a message to the child process child.send({msg: "Foo"});
这里是subprocess的代码(intensiveTask.js)
process.on('message', function(data) { //do the intensive work here var output=data.msg + " Bar"; //send the output back to the parent process.send({msg: output}); });