javascript - Nodejs非阻塞的理解
ringa_lee
ringa_lee 2017-04-10 14:53:34
[JavaScript讨论组]

主程序:

var http = require('http');
var url = require('url');
var cp = require('child_process');

function onRequest(request, response) {
    var pathname = url.parse(request.url).pathname;
    if( pathname == '/wait' ) {
        console.log("Will wait!");
        cp.exec('node applications\\demo\\block.js', [], myCallback);
        console.log(new Date());
    }
    else{
        response.writeHead(200, {'Content-Type': 'text/plain'});
        response.write('Hello!\n');
        response.end();
    }

    console.log('Cool ' + (new Date()));

    function myCallback(){
        console.log("ok: " + (new Date()));
        response.writeHead(200, {'Content-Type': 'text/plain'});
        response.write('Thanks for waiting!\n');
        response.end();
    }
}
http.createServer(onRequest).listen(8081);
console.log('Server started');

exec调用的block.js是(即休眠10秒):

var startTime = new Date().getTime();
while (new Date().getTime() < startTime + 10000);

如果我访问http://localhost:8081/wait,会进入pathname == '/wait'的语句,并且通过exec调用block.js休眠10秒。这时我在休眠结束之前迅速的访问http://localhost:8081/,迅速返回结果。这个我认为是正常的。

但是如果我同时打开三个http://localhost:8081/wait链接,发现第一个链接大约花10秒,第二个链接大约花20秒,第三个链接大约花30秒(从console的输出看他们是串行的)。通过任务管理器看到只多了一个node进程(win 7操作系统,四核)。难道这三次访问exec不应该开三个block.js进程吗?请教该如何理解这段代码和这个现象?
Nodejs所说的能同时处理多个请求到底该如何理解呢?

附上console输出:

Server started
Will wait!
Sun Jan 25 2015 00:59:50 GMT+0800 (中国标准时间)
Cool Sun Jan 25 2015 00:59:50 GMT+0800 (中国标准时间)
ok: Sun Jan 25 2015 01:00:01 GMT+0800 (中国标准时间)
Will wait!
Sun Jan 25 2015 01:00:21 GMT+0800 (中国标准时间)
Cool Sun Jan 25 2015 01:00:21 GMT+0800 (中国标准时间)
ok: Sun Jan 25 2015 01:00:31 GMT+0800 (中国标准时间)
Will wait!
Sun Jan 25 2015 01:00:31 GMT+0800 (中国标准时间)
Cool Sun Jan 25 2015 01:00:31 GMT+0800 (中国标准时间)
ok: Sun Jan 25 2015 01:00:41 GMT+0800 (中国标准时间)
ringa_lee
ringa_lee

ringa_lee

全部回复(0)
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号