Deep understanding of Node async and event loop

Node was originally born to build a high-performance web server. As a JavaScript server runtime, it has the characteristics of event-driven, asynchronous I/O, and single thread. The asynchronous programming model based on the event loop enables Node to handle high concurrency, which greatly improves the performance of the server. At the same time, because the single-threaded feature of JavaScript is maintained, Node does not need to deal with problems such as state synchronization and deadlock under multi-threading, and also There is no performance overhead caused by thread context switching. Based on these characteristics, Node has the inherent advantages of high performance and high concurrency, and can build various high-speed and scalable network application platforms based on it.

This article will dive into the underlying implementation and execution mechanism of Node asynchrony and event loop, hoping to help you.

Why asynchronous?

Why does Node use async as its core programming model?

As mentioned earlier, Node was originally born to build a high-performance web server. Assuming that there are several sets of unrelated tasks to be completed in the business scenario, the modern mainstream solutions are as follows:

  • Single-threaded serial execution.

  • Multithreading is done in parallel.

Single-threaded serial execution is a synchronous programming model. Although it is more in line with the programmer's thinking method of thinking in sequence, it is easy to write more convenient code, but because it is synchronously executing I/O, it can only process at the same time. A single request will cause the server to respond slowly, which cannot be applied in high-concurrency application scenarios, and because it is blocking I/O, the CPU will always wait for the I/O to complete and cannot do other things, so that the processing capacity of the CPU is insufficient. To make full use of, eventually lead to low efficiency,

The multi-threaded programming model will also cause headaches for developers due to problems such as state synchronization and deadlock in programming. Although multi-threading can effectively improve CPU utilization on multi-core CPUs.

Although the programming model of single-threaded serial execution and multi-threaded parallel execution has its own advantages, it also has shortcomings in terms of performance and development difficulty.

In addition, starting from the speed of responding to client requests, if the client obtains two resources at the same time, the response speed of the synchronous mode will be the sum of the response speeds of the two resources, and the response speed of the asynchronous mode will be between the two The biggest one, the performance advantage is very obvious compared to synchronization. As the complexity of the application increases, the scenario will evolve into responding to n requests at the same time, and the advantages of asynchronous over synchronization will be highlighted.

To sum up, Node gives its answer: use a single thread to avoid problems such as multi-threaded deadlock and state synchronization; use asynchronous I/O to keep a single thread away from blocking to better utilize the CPU. This is why Node uses asynchrony as its core programming model.

In addition, in order to make up for the disadvantage that a single thread cannot take advantage of multi-core CPUs, Node also provides subprocesses similar to Web Workers in browsers, which can efficiently utilize CPUs through worker processes.

How to achieve asynchrony?

After talking about why use asynchrony, how to implement asynchrony?

There are two types of asynchronous operations that we usually call: one is operations related to I/O such as file I/O and network I/O; the other is operations that are setTimeOutnot setIntervalrelated to I/O such as I/O. It is clear that the asynchronous we are talking about refers to operations related to I/O, ie asynchronous I/O.

The proposal of asynchronous I/O is to expect that I/O calls will not block the execution of subsequent programs, and the original waiting time for I/O completion is allocated to the rest of the required business for execution. To do this, you need to use non-blocking I/O.

Blocking I/O means that the CPU will always block after initiating an I/O call, waiting for the I/O to complete. Knowing blocking I/O, non-blocking I/O is easy to understand. The CPU will return immediately after initiating an I/O call instead of blocking waiting. Before the I/O is completed, the CPU can process other transactions. Obviously, compared to blocking I/O, non-blocking I/O is more than a performance improvement.

So, since non-blocking I/O is used, the CPU can return immediately after initiating the I/O call, so how does it know that the I/O is complete? The answer is polling.

In order to obtain the status of the I/O call in time, the CPU will repeatedly call the I/O operation to confirm whether the I/O has been completed. This technique of repeatedly calling to determine whether the operation is completed is called polling.

Obviously, polling will cause the CPU to repeatedly perform state judgment, which is a waste of CPU resources. Moreover, the polling interval is difficult to control. If the interval is too long, the completion of the I/O operation will not receive a timely response, which will indirectly reduce the response speed of the application; if the interval is too short, the CPU will inevitably spend time polling. It takes longer and reduces the utilization of CPU resources.

因此,轮询虽然满足了非阻塞 I/O 不会阻塞后续程序的执行的要求,但是对于应用程序而言,它仍然只能算是一种同步,因为应用程序仍然需要等待 I/O 完全返回,依旧花费了很多时间来等待。

我们所期望的完美的异步 I/O,应该是应用程序发起非阻塞调用,无须通过轮询的方式不断查询 I/O 调用的状态,而是可以直接处理下一个任务,在 I/O 完成后通过信号量或回调将数据传递给应用程序即可。

如何实现这种异步 I/O 呢?答案是线程池。

虽然本文一直提到,Node 是单线程执行的,但此处的单线程是指 JavaScript 代码是执行在单线程上的,对于 I/O 操作这类与主业务逻辑无关的部分,通过运行在其他线程的方式实现,并不会影响或阻塞主线程的运行,反而可以提高主线程的执行效率,实现异步 I/O。

通过线程池,让主线程仅进行 I/O 的调用,让其他多个线程进行阻塞 I/O 或者非阻塞 I/O 加轮询技术完成数据获取,再通过线程之间的通信将 I/O 得到的数据进行传递,这就轻松实现了异步 I/O:

image-20220703233325903.png

主线程进行 I/O 调用,而线程池进行 I/O 操作,完成数据的获取,然后通过线程之间的通信将数据传递给主线程,即可完成一次 I/O 的调用,主线程再利用回调函数,将数据暴露给用户,用户再利用这些数据来完成业务逻辑层面的操作,这就是 Node 中一次完整的异步 I/O 流程。而对于用户来说,不必在意底层这些繁琐的实现细节,只需要调用 Node 封装好的异步 API,并传入处理业务逻辑的回调函数即可,如下所示:

const fs = require("fs");

fs.readFile('example.js', (data) => {
  // 进行业务逻辑的处理
});

Node 的异步底层实现机制在不同平台下有所不同:Windows 下主要通过 IOCP 来向系统内核发送 I/O 调用和从内核获取已完成的 I/O 操作,配以事件循环,以此完成异步 I/O 的过程;Linux 下通过 epoll 实现这个过程;FreeBSD下通过 kqueue 实现,Solaris 下通过 Event ports 实现。线程池在 Windows 下由内核(IOCP)直接提供,*nix 系列则由 libuv 自行实现。

由于 Windows 平台和 *nix 平台的差异,Node 提供了 libuv 作为抽象封装层,使得所有平台兼容性的判断都由这一层来完成,保证上层的 Node 与下层的自定义线程池及 IOCP 之间各自独立。Node 在编译期间会判断平台条件,选择性编译 unix 目录或是 win 目录下的源文件到目标程序中:

image.png

以上就是 Node 对异步的实现。

(线程池的大小可以通过环境变量 UV_THREADPOOL_SIZE 设置,默认值为 4,用户可结合实际情况来调整这个值的大小。)

那么问题来了,在得到线程池传递过来的数据后,主线程是如何、何时调用回调函数的呢?答案是事件循环。

基于事件循环的异步编程模型

既然使用回调函数来进行对 I/O 数据的处理,就必然涉及到何时、如何调用回调函数的问题。在实际开发中,往往会涉及到多个、多类异步 I/O 调用的场景,如何合理安排这些异步 I/O 回调的调用,确保异步回调的有序进行是一个难题,而且,除了异步 I/O 之外,还存在定时器这类非 I/O 的异步调用,这类 API 实时性强,优先级相应地更高,如何实现不同优先级回调地调度呢?

因此,必须存在一个调度机制,对不同优先级、不同类型的异步任务进行协调,确保这些任务在主线程上有条不紊地运行。与浏览器一样,Node 选择了事件循环来承担这项重任。

Node 根据任务的种类和优先级将它们分为七类:Timers、Pending、Idle、Prepare、Poll、Check、Close。对于每类任务,都存在一个先进先出的任务队列来存放任务及其回调(Timers 是用小顶堆存放)。基于这七个类型,Node 将事件循环的执行分为如下七个阶段:

timers

这个阶段的执行优先级是最高的。

事件循环在这个阶段会检查存放定时器的数据结构(最小堆),对其中的定时器进行遍历,逐个比较当前时间和过期时间,判断该定时器是否过期,如果过期的话,就将该定时器的回调函数取出并执行。

pending

该阶段会执行网络、IO 等异常时的回调。一些 *nix 上报的错误,在这个阶段会得到处理。另外,一些应该在上轮循环的 poll 阶段执行的 I/O 回调会被推迟到这个阶段执行。

idle、prepare

这两个阶段仅在事件循环内部使用。

poll

检索新的 I/O 事件;执行与 I/O 相关的回调(除了关闭回调、定时器调度的回调和 之外几乎所有回调setImmediate());节点会在适当的时候阻塞在这里。

poll,即轮询阶段是事件循环最重要的阶段,网络 I/O、文件 I/O 的回调都主要在这个阶段被处理。该阶段有两个主要功能:

  1. 计算该阶段应该阻塞和轮询 I/O 的时间。

  2. 处理 I/O 队列中的回调。

当事件循环进入 poll 阶段并且没有设置定时器时:

  • 如果轮询队列不为空,则事件循环将遍历该队列,同步地执行它们,直到队列为空或达到可执行的最大数量。

  • 如果轮询队列为空,则会发生另外两种情况之一:

    • 如果有 setImmediate() 回调需要执行,则立即结束 poll 阶段,并进入 check 阶段以执行回调。

    • 如果没有 setImmediate() 回调需要执行,事件循环将停留在该阶段以等待回调被添加到队列中,然后立即执行它们。在超时时间到达前,事件循环会一直停留等待。之所以选择停留在这里是因为 Node 主要是处理 IO 的,这样可以更及时地响应 IO。

一旦轮询队列为空,事件循环将检查已达到时间阈值的定时器。如果有一个或多个定时器达到时间阈值,事件循环将回到 timers 阶段以执行这些定时器的回调。

check

该阶段会依次执行 setImmediate() 的回调。

close

该阶段会执行一些关闭资源的回调,如 socket.on('close', ...)。该阶段晚点执行也影响不大,优先级最低。

当 Node 进程启动时,它会初始化事件循环,执行用户的输入代码,进行相应异步 API 的调用、计时器的调度等等,然后开始进入事件循环:

   ┌───────────────────────────┐
┌─>│           timers          │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │     pending callbacks     │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
│  │       idle, prepare       │
│  └─────────────┬─────────────┘      ┌───────────────┐
│  ┌─────────────┴─────────────┐      │   incoming:   │
│  │           poll            │<─────┤  connections, │
│  └─────────────┬─────────────┘      │   data, etc.  │
│  ┌─────────────┴─────────────┐      └───────────────┘
│  │           check           │
│  └─────────────┬─────────────┘
│  ┌─────────────┴─────────────┐
└──┤      close callbacks      │
   └───────────────────────────┘

事件循环的每一轮循环(通常被称为 tick),会按照如上给定的优先级顺序进入七个阶段的执行,每个阶段会执行一定数量的队列中的回调,之所以只执行一定数量而不全部执行完,是为了防止当前阶段执行时间过长,避免下一个阶段得不到执行。

OK,以上就是事件循环的基本执行流程。现在让我们来看另外一个问题。

对于以下这个场景:

const server = net.createServer(() => {}).listen(8080);

server.on('listening', () => {});

当服务成功绑定到 8000 端口,即 listen() 成功调用时,此时 listening 事件的回调还没有绑定,因此端口成功绑定后,我们所传入的 listening 事件的回调并不会执行。

再思考另外一个问题,我们在开发中可能会有一些需求,如处理错误、清理不需要的资源等等优先级不是那么高的任务,如果以同步的方式执行这些逻辑,就会影响当前任务的执行效率;如果以异步的方式,比如以回调的形式传入 setImmediate() 又无法保证它们的执行时机,实时性不高。那么要如何处理这些逻辑呢?

基于这几个问题,Node 参考了浏览器,也实现了一套微任务的机制。在 Node 中,除了调用 new Promise().then() 所传入的回调函数会被封装成微任务外,process.nextTick() 的回调也会被封装成微任务,并且后者的执行优先级比前者高。

有了微任务后,事件循环的执行流程又是怎么样的呢?换句话说,微任务的执行时机在什么时候?

  • 在 node 11 及 11 之后的版本,一旦执行完一个阶段里的一个任务就立刻执行微任务队列,清空该队列。

  • 在 node11 之前执行完一个阶段后才开始执行微任务。

因此,有了微任务后,事件循环的每一轮循环,会先执行 timers 阶段的一个任务,然后按照先后顺序清空 process.nextTick()new Promise().then() 的微任务队列,接着继续执行 timers 阶段的下一个任务或者下一个阶段,即 pending 阶段的一个任务,按照这样的顺序以此类推。

利用 process.nextTick(),Node 就可以解决上面的端口绑定问题:在 listen() 方法内部,listening 事件的发出会被封装成回调传入 process.nextTick() 中,如下伪代码所示:

function listen() {
    // 进行监听端口的操作
    ...
    // 将 `listening` 事件的发出封装成回调传入 `process.nextTick()` 中
    process.nextTick(() => {
        emit('listening');
    });
};

在当前代码执行完毕后便会开始执行微任务,从而发出 listening 事件,触发该事件回调的调用。

一些注意事项

由于异步本身的不可预知性和复杂性,在使用 Node 提供的异步 API 的过程中,尽管我们已经掌握了事件循环的执行原理,但是仍可能会有一些不符合直觉或预期的现象产生。

比如定时器(setTimeoutsetImmediate)的执行顺序会因为调用它们的上下文而有所不同。如果两者都是从顶层上下文中调用的,那么它们的执行时间取决于进程或机器的性能。

我们来看以下这个例子:

setTimeout(() => {
  console.log('timeout');
}, 0);

setImmediate(() => {
  console.log('immediate');
});

以上代码的执行结果是什么呢?按照我们刚才对事件循环的描述,你可能会有这样的答案:由于 timers 阶段会比 check 阶段先执行,因此 setTimeout() 的回调会先执行,然后再执行 setImmediate() 的回调。

实际上,这段代码的输出结果是不确定的,可能先输出 timeout,也可能先输出 immediate。这是因为这两个定时器都是在全局上下文中调用的,当事件循环开始运行并执行到 timers 阶段时,当前时间可能大于 1 ms,也可能不足 1 ms,具体取决于机器的执行性能,因此 setTimeout() 在第一个 timers 阶段是否会被执行实际上是不确定的,因此才会出现不同的输出结果。

(当 delaysetTimeout 的第二个参数)的值大于 2147483647 或小于 1 时, delay 会被设置为 1。)

我们接着看下面这段代码:

const fs = require('fs');

fs.readFile(__filename, () => {
  setTimeout(() => {
    console.log('timeout');
  }, 0);
  setImmediate(() => {
    console.log('immediate');
  });
});

可以看到,在这段代码中两个定时器都被封装成回调函数传入 readFile 中,很明显当该回调被调用时当前时间肯定大于 1 ms 了,所以 setTimeout 的回调会比 setImmediate 的回调先得到调用,因此打印结果为:timeout immediate

以上是在使用 Node 时需要注意的与定时器相关的事项。除此之外,还需注意 process.nextTick()new Promise().then() 还有 setImmediate() 的执行顺序,由于这部分比较简单,前面已经提到过,就不再赘述了。

总结

文章开篇从为什么要异步、如何实现异步两个角度出发,较详细地阐述了 Node 事件循环的实现原理,并提到一些需要注意的相关事项,希望对你有所帮助。

如果觉得这篇文章写的不错的话,就请给我点个赞吧!

参考资料

Guess you like

Origin juejin.im/post/7121719645710581767