Analysis of the event loop in Node

不言
Release: 2018-07-20 10:30:00
Original
1247 people have browsed it

This article introduces to you the analysis of the event loop in Node. It has certain reference value. Friends in need can refer to it.

Each stage in the event loop

The event loop process of Node.js is roughly as follows:

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

Each stage has its own task queue. When the task of this stage After all queues have been executed, or the maximum number of tasks executed has been reached, it will enter the next stage.

timers phase

This phase will execute the scheduled tasks set bysetTimeoutandsetInterval.
Of course, this timing is not accurate, but after the timing time is exceeded, once the execution opportunity is obtained, it will be executed immediately.

pending callbacks stage

This stage will perform some operations related to the underlying system, such as errors returned by TCP connections, etc. When these errors occur, they will be postponed by Node to the next cycle.

Polling phase

This phase is used to execute callbacks related to IO operations. Node will ask the operating system whether a new IO event has been triggered, and then execute the corresponding event. callback. Almost all operations except timer events,setImmediate()andclose callbackswill be performed during this phase.

check phase

This phase will execute the tasks set bysetImmediate().

close callbacks phase

If asocketorhandle(handle)is suddenly closed, for example throughsocket.destroy()is closed, thecloseevent will be emitted at this stage.

Specific execution of the event loop

After the event loop is initialized, it will proceed according to the process shown in the figure above:

  1. First, the timer will be executed in sequence Tasks inpending callbackcallback;

  2. and then enters theidleandpreparestages, where Node will be executed Some internal logic;

  3. and then enters thepollpolling phase. At this stage, all IO callbacks will be executed, such as reading files, network operations, etc. Thepollstage has apoll queuetask queue. The execution process of this stage is relatively long, as follows:

  • Entering this stage, it will first check whether thetimeouttiming queue is available. The executed task, if any, will jump to thetimer stagefor execution.

  • If there is notimer task, thepoll queuetask queue will be checked. If it is not empty, all tasks will be traversed and executed until they are all The execution is completed or the maximum number of tasks that can be executed is reached.

  • poll queueAfter the task queue is executed, it will check whether there are tasks in thesetImmediatetask queue. If so, the event loop will transfer Go to the nextcheckstage.

  • If there is nosetImmediatetask, then Node will wait here for the arrival of new IO callbacks and execute them immediately.

Note: This waiting will not continue forever. Instead, after reaching a certain limit, it will continue to the next stage for execution.

setTimeout()andsetImmediate()

A little secret

It’s not actually a secret, but I’m I just found out after checking the information.
That is: in Node,setTimeout(callback, 0)will be converted tosetTimeout(callback, 1).
Please refer here for details.

setTimeout()andsetImmediate()Execution order

The execution order of the following two scheduled tasks performs inconsistently under different circumstances. .

setTimeout(function() { console.log('timeout'); }, 0); setImmediate(function() { console.log('immediate'); });
Copy after login

Set the timer in ordinary code

If you set these two scheduled tasks in the ordinary code execution stage (for example, in the outermost code block), their execution order is different. stable.

  1. First of all, thesetTimeout(callback, 0)we set has been converted intosetTimeout(callback, 1), so enterTimerDuring the stage, it will be judged based on the current time whether the timing exceeds1ms.

  2. Before the event loop enters the timer phase, the system calls a method to update the current time. Since other programs are running in the system at the same time, the system needs to wait for the processes of other programs to end. Get the accurate time, so there may be a certain delay in updating the time.

  3. When updating the time, if there is no delay, the timing is less than1ms,immediateThe task will be executed first; if there is a delay, and this time When the limit of1msis reached, thetimeouttask will be executed first.

Set the timer in the IO callback

If we set these two timers in the IO callback, then thesetImmediatetask will first Executed for the following reasons:

  1. 进入poll phase轮询阶段之前会先检查是否有timer定时任务。

  2. 如果没有timer定时任务,才会执行后面的 IO 回调。

  3. 我们在 IO 回调中设置setTimeout定时任务,这时已经过了timer检查阶段,所以timer定时任务会被推迟到下一个循环中执行。

process.nextTick()

无论在事件循环的哪个阶段,只要使用process.nextTick()添加了回调任务,Node 都会在进入下一阶段之前把nextTickQueue队列中的任务执行完。

setTimeout(function() { setImmediate(() => { console.log('immediate'); }); process.nextTick(() => { console.log('nextTick'); }); }, 0); // nextTick // immediate
Copy after login

上述代码中,总是先执行nextTick任务,就是因为在循环在进入下一个阶段之前会先执行nextTickQueue中的任务。下面代码的执行结果也符合预期。

setImmediate(() => { setTimeout(() => { console.log('timeout'); }, 0); process.nextTick(() => { console.log('nextTick'); }); }); // nextTick // timeout
Copy after login

相关推荐:

关于Node异步 I/O的介绍

关于Node模块机制的解析

The above is the detailed content of Analysis of the event loop in Node. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!