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.
The event loop process of Node.js is roughly as follows:
┌───────────────────────────┐ ┌─>│ timers │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ pending callbacks │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ │ │ idle, prepare │ │ └─────────────┬─────────────┘ ┌───────────────┐ │ ┌─────────────┴─────────────┐ │ incoming: │ │ │ poll │<─────┤ connections, │ │ └─────────────┬─────────────┘ │ data, etc. │ │ ┌─────────────┴─────────────┐ └───────────────┘ │ │ check │ │ └─────────────┬─────────────┘ │ ┌─────────────┴─────────────┐ └──┤ close callbacks │ └───────────────────────────┘
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.
This phase will execute the scheduled tasks set by setTimeout
and setInterval
.
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.
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.
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()
and close callbacks
will be performed during this phase.
This phase will execute the tasks set by setImmediate()
.
If a socket
or handle(handle)
is suddenly closed, for example through socket.destroy()
is closed, the close
event will be emitted at this stage.
After the event loop is initialized, it will proceed according to the process shown in the figure above:
First, the timer will be executed in sequence Tasks in pending callback
callback;
and then enters the idle
and prepare
stages, where Node will be executed Some internal logic;
and then enters the poll
polling phase. At this stage, all IO callbacks will be executed, such as reading files, network operations, etc. The poll
stage has a poll queue
task queue. The execution process of this stage is relatively long, as follows:
Entering this stage, it will first check whether the timeout
timing queue is available. The executed task, if any, will jump to the timer stage
for execution.
If there is no timer task
, the poll queue
task 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 queue
After the task queue is executed, it will check whether there are tasks in the setImmediate
task queue. If so, the event loop will transfer Go to the next check
stage.
If there is no setImmediate
task, 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()
and setImmediate()
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 to setTimeout(callback, 1)
.
Please refer here for details.
setTimeout()
and setImmediate()
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'); });
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.
First of all, the setTimeout(callback, 0)
we set has been converted into setTimeout(callback, 1)
, so enter Timer
During the stage, it will be judged based on the current time whether the timing exceeds 1ms
.
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.
When updating the time, if there is no delay, the timing is less than 1ms
,immediate
The task will be executed first; if there is a delay, and this time When the limit of 1ms
is reached, the timeout
task will be executed first.
If we set these two timers in the IO callback, then the setImmediate
task will first Executed for the following reasons:
进入 poll phase
轮询阶段之前会先检查是否有 timer
定时任务。
如果没有 timer
定时任务,才会执行后面的 IO 回调。
我们在 IO 回调中设置 setTimeout
定时任务,这时已经过了 timer
检查阶段,所以 timer
定时任务会被推迟到下一个循环中执行。
process.nextTick()
无论在事件循环的哪个阶段,只要使用 process.nextTick()
添加了回调任务,Node 都会在进入下一阶段之前把 nextTickQueue
队列中的任务执行完。
setTimeout(function() { setImmediate(() => { console.log('immediate'); }); process.nextTick(() => { console.log('nextTick'); }); }, 0); // nextTick // immediate
上述代码中,总是先执行 nextTick
任务,就是因为在循环在进入下一个阶段之前会先执行 nextTickQueue
中的任务。下面代码的执行结果也符合预期。
setImmediate(() => { setTimeout(() => { console.log('timeout'); }, 0); process.nextTick(() => { console.log('nextTick'); }); }); // nextTick // timeout
相关推荐:
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!