Node: The basic element of I/O asynchronous

Node.js: the basic elements of asynchronous I/O

1. Event loop

Node's execution model is an event loop, which makes callback functions very common;

Every time a process starts, Node will create an infinite loop, and each loop is called a Tick. The process of each tick is to check whether there are any pending events, if so, call its related callback function; if there are still related callback functions, execute them; if there are no more event processing, exit the event loop.

2. Observer Mode

In each cycle, there are one or more observers. The process of judging whether there is an event to be processed is that the observer asks whether there is an event that needs to be processed.

The event loop is a typical producer and consumer relationship. Asynchronous I/O, network requests, etc. are event producers, which continuously provide Node with different types of events. These events are passed to the observer, and the event loop takes out the events from the observer and processes them.

3. Request object

The request object is an important intermediate product in the asynchronous I/O process. All the state is stored in this object, including being sent to the thread pool to wait for execution and the callback processing after the I/O operation is completed.

4. Execute callback

The behavior of the I/O observer callback function is to take out the result attribute of the request object as a parameter, take out the oncomplete_sym attribute as a method, and then call execution to achieve the purpose of calling the callback function passed in JavaScript.


Event loops, observers, request objects, and I/O thread pools constitute the basic elements of Node's asynchronous I/O model.

Since we know that JavaScript is single-threaded, it is easy to understand by common sense that it cannot make full use of multi-core CPUs. In fact, in Node, in addition to JavaScript is single-threaded, Node itself is actually multi-threaded , but the I/O thread uses less CPU.

Guess you like

Origin blog.csdn.net/yivisir/article/details/107788688