In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces the browser and Node.js is how to design EventLoop, the article is very detailed, has a certain reference value, interested friends must read!
Event Loop of the browser
JavaScript is used to implement web page interaction logic, involving dom operations. If multiple threads operate at the same time, they need to do synchronous mutual exclusion. In order to simplify, it is designed as a single thread, but if a single thread encounters timing logic and network requests will block. What should I do?
You can add a layer of scheduling logic. Encapsulate the JS code into individual tasks, put them in a task queue, and the main thread will continue to fetch and execute the tasks.
Each time the fetch task is executed, a new call stack is created.
Among them, timers and network requests are actually executed by other threads, and after execution, a task is put in the task queue to tell the main thread that it can continue to execute.
Because these asynchronous tasks are executed by other threads and then notified to the main thread through the task queue, it is an event mechanism, so this loop is called Event Loop.
These asynchronous tasks performed on other threads include timers (setTimeout, setInterval), UI rendering, and network requests (XHR or fetch).
However, the current Event Loop has a serious problem, there is no concept of priority, just according to the order of execution, then if there are high-priority tasks will not be executed in time. Therefore, it is necessary to design a queue-jumping mechanism.
It would be nice to have a high-priority task queue. After each ordinary task, all the high-priority tasks are executed, and then the ordinary tasks are executed.
With the queue jumping mechanism, high-priority tasks can be carried out in a timely manner.
This is the Event Loop of the current browser.
The common task is called MacroTask (macro task), and the high-priority task is called MicroTask (micro task).
Macro tasks include: setTimeout, setInterval, requestAnimationFrame, Ajax, fetch, script tag code.
Micro tasks include: Promise.then, MutationObserver, Object.observe.
How to understand the division of macro and micro tasks?
Timers and network requests are all common asynchronous logic that notifies the main thread after other threads have finished running, so they are all macro tasks.
These three types of high-quality tasks are also easy to understand. Both MutationObserver and Object.observe listen for changes in an object, and the change is very instantaneous. You must respond immediately, otherwise it may change again. Promise organizes asynchronous processes, and calling then at the end of asynchronism is also highly excellent.
This is the design of Event Loop in the browser: the Loop mechanism and Task queue are designed to support asynchronism and solve the problem of logic execution blocking the main thread, and the queue jumping mechanism of MicroTask queue is designed to solve the problem of early execution of high-priority tasks.
But later, JS's execution environment is not just a browser, but also Node.js, which also has to solve these problems, but it designs a more detailed Event Loop.
Event loop of Node.js
Node is a new JS runtime environment that also supports asynchronous logic, including timers, IO, network requests and, obviously, Event Loop.
However, the browser Event Loop is designed for browsers, and the design is still a little rough for high-performance servers.
Where is it rough?
The browser's Event Loop is only divided into two levels of priority, one is macro tasks, and the other is micro tasks. But there is no more priority between macro tasks and no priority between micro tasks.
There is also a priority between Node.js task macro tasks. For example, the logic of timer Timer is higher than that of IO, because when it comes to time, the earlier the more accurate, while the logic priority of close resources is very low, because it does not have much impact on resources such as memory, which is not occupied by close.
So the macro task queue is split into five priorities: Timers, Pending, Poll, Check, and Close.
Explain these five macro tasks:
Timers Callback: when it comes to time, the earlier the execution is, the more accurate it is, so the highest priority is easy to understand.
Pending Callback: callback when handling network, IO and other exceptions. Some * niux systems will wait for the error to be reported, so they have to deal with it.
Poll Callback: the data that deals with IO, the connection of the network, this is what the server mainly deals with.
Check Callback: executes the callback of setImmediate, which is characterized by the callback right after the execution of IO.
Close Callback: the callback of the resource is turned off, the delayed execution will not affect it, and the priority is the lowest.
So, Node.js 's Event Loop runs like this:
There is another difference to pay special attention to:
Node.js 's Event Loop is not the kind of browser that executes one macro task at a time, and then executes all the micro tasks, but executes a certain number of Timers macro tasks, then executes all the micro tasks, then executes a certain number of Pending macro tasks, and then executes all the micro tasks, as well as the remaining Poll, Check, and Close macro tasks. (revision: this was the case before node 11, but after node 11, every macro task performs all micro tasks.)
Why is that?
In fact, it's easy to understand in terms of priority:
Suppose the priority of the macro task in the browser is 1, so it is executed in order, that is, a macro task, all the micro tasks, another macro task, and then all the micro tasks.
There is also a priority between Node.js 's macro tasks, so every time Node.js 's Event Loop runs all the current priority macro tasks before running the micro task, and then the next priority macro task.
That is, a certain number of Timers macro tasks, then all micro tasks, then a certain number of Pending Callback macro tasks, and then all micro tasks.
Why is it a certain number?
Because if there are too many macro tasks in one stage, the next stage will not be executed all the time, so there is an upper limit, and the rest of the next Event Loop will continue.
In addition to the priority of macro tasks, micro tasks are also prioritized, adding a process.nextTick high priority micro task to run before all ordinary micro tasks.
So, the complete process of Node.js 's Event Loop goes like this:
Timers phase: execute a certain number of timers, that is, callback of setTimeout and setInterval. If too many timers are left for next execution,
Microtasks: perform all nextTick microtasks, and then perform other ordinary microtasks
Pending phase: execute a certain number of IO and network exception callbacks, and leave too many for the next execution
Microtasks: perform all nextTick microtasks, and then perform other ordinary microtasks
Idle/Prepare phase: a phase for internal use
Microtasks: perform all nextTick microtasks, and then perform other ordinary microtasks
Poll phase: execute data callback of a certain number of files, connection callback of the network, and save too many for the next execution. If there is no IO callback and there are no callbacks for timers or check phases to handle, just block here and wait for the IO event
Microtasks: perform all nextTick microtasks, and then perform other ordinary microtasks
Check phase: execute a certain number of callback of setImmediate, if too much, save it for next execution.
Microtasks: perform all nextTick microtasks, and then perform other ordinary microtasks
Close phase: callback that executes a certain number of close events, leaving too many for the next execution.
Microtasks: perform all nextTick microtasks, and then perform other ordinary microtasks
It's obviously a lot more complicated than the Event Loop in the browser, but after our previous analysis, we can also understand:
Node.js prioritizes macro tasks, which are Timers, Pending, Poll, Check and Close from high to low. It also divides micro tasks, that is, nextTick micro tasks and other micro tasks. The execution process is to first execute a certain number of macro tasks of the current priority (save the rest for the next loop), then execute process.nextTick micro-tasks, then perform ordinary micro-tasks, and then execute a certain number of macro tasks of the next priority. It goes on and on like this. There is also an Idle/Prepare phase for the internal logic of Node.js and does not need to be concerned.
Changed the way the browser Event Loop executes one macro task at a time, allowing high-priority macro tasks to be executed earlier, but also set an upper limit to prevent the next stage from not being executed.
Another point to pay special attention to is the poll phase: if you run to the poll phase and find that the poll queue is empty and the timers queue and the check queue have no tasks to execute, then block and wait for the IO event here instead of idling. This is also designed because the server is mainly dealing with IO, where blocking can respond to IO earlier.
The Event Loop of a complete Node.js looks like this:
Compare the Event Loop of the browser:
The overall design ideas of the Event Loop of the two JS operating environments are similar, but the Event Loop of Node.js makes a finer-grained division of macro tasks and micro tasks, which is easy to understand. after all, the environment that Node.js faces is different from that of browsers, and more importantly, the server will have higher performance requirements.
Summary
JavaScript was originally used to write web page interaction logic. In order to avoid the synchronization problem of multi-thread modifying dom at the same time, a single thread was designed, and in order to solve the blocking problem of single thread, a layer of scheduling logic, that is, Loop loop and Task queue, was added, and the blocking logic was put to other threads to run, thus supporting asynchronism. Then, in order to support high-priority task scheduling, micro-task queues are introduced, which is the browser's Event Loop mechanism: execute one macro task at a time, and then execute all the micro-tasks.
Node.js is also a JS running environment. Event Loop is also needed to support asynchronism, but the server environment is more complex and requires higher performance, so Node.js prioritizes both macro and micro tasks with finer granularity:
Node.js is divided into five kinds of macro tasks, namely Timers, Pending, Poll, Check, and Close. It is divided into two kinds of micro-tasks, which are process.nextTick micro-tasks and other micro-tasks.
The Event Loop process of Node.js is to execute a certain number of macro tasks in the current stage (the rest will be executed in the next loop), and then execute all the micro tasks, which have six phases: Timers, Pending, Idle/Prepare, Poll, Check, and Close. (revision: this was the case before node 11, but after node 11, every macro task performs all micro tasks.)
The Idle/Prepare phase is used internally in Node.js, so don't worry about it.
It is particularly important to note that in the Poll phase, if the poll queue is empty and the timers and check queues are also empty, you will block and wait for IO until there is a callback in the timers and check queues before continuing loop.
Event Loop is a set of scheduling logic designed by JS to support asynchronism and task priority. There are different designs for different environments such as browser and Node.js (mainly because the granularity of task priority division is different). Node.js faces a more complex environment and higher performance requirements, so the design of Event Loop is more complex.
The above is all the content of the article "how browsers and Node.js design EventLoop". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.