【问题标题】:Getting really confused with Node.js single thread execution model对 Node.js 单线程执行模型感到非常困惑
【发布时间】:2012-08-23 18:38:05
【问题描述】:

好的,我正在学习 Node.js,但我无法完全理解这个等待模型。我通过阅读The Node Beginner Book 来学习它。其中有一个关于阻塞和非阻塞操作的部分。我不明白的是非阻塞操作。

代码如下:

var exec = require("child_process").exec;

function start(response) {
  console.log("Request handler 'start' was called.");

  exec("ls -lah", function (error, stdout, stderr) {
    response.writeHead(200, {"Content-Type": "text/plain"});
    response.write(stdout);
    response.end();
  });
}

function upload(response) {
  console.log("Request handler 'upload' was called.");
  response.writeHead(200, {"Content-Type": "text/plain"});
  response.write("Hello Upload");
  response.end();
}

exports.start = start;
exports.upload = upload;

启动函数调用exec,exec执行ls -lah。那么回调会等待响应吗?如果 exec 执行“find /”怎么办,在我的计算机中完成“find /”命令需要大约 30 秒。由于这是单线程的,如果用户 1 访问启动函数,那么在毫秒内用户 2 也访问启动函数。然后会发生什么?这是否意味着用户 1 将在 30 秒内得到响应,而用户 2 需要等待 1 分钟,因为用户 1 仍在执行“查找 /”?

对不起,如果我的问题太幼稚了。感谢阅读!

【问题讨论】:

    标签: node.js


    【解决方案1】:

    在 node.js 中,所有 I/O 操作都是异步进行的。两个find 操作将并行运行。试试看这个:Understanding the node.js event loop

    【讨论】:

      猜你喜欢
      • 2014-10-08
      • 2012-08-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-17
      • 1970-01-01
      • 2022-01-03
      相关资源
      最近更新 更多