Node.js Event-Driven _node.js

Source: Internet
Author: User

Node.js Event-Driven implementation overview

While it is not (and is not necessary) to specify "events" in the ECMAScript standard, events are in the browser an extremely important mechanism for giving JavaScript the ability to respond to user actions and DOM changes In Node.js, the asynchronous event-driven model is the foundation of its high concurrency capability.

Learning JavaScript also needs to understand its operating platform, in order to better understand the JavaScript event model, I intend to start with node and browser engine source code, analysis of its underlying implementation, and my analysis as a series of blog, on the other hand, as a note, but also hope to communicate with you , analysis and understanding of the omission of bias, but also hope that you treatise.

Brief description of event-driven model

There are a lot of good articles that explain the JavaScript event model itself, and it's already a rotten topic, and I'll just write it down and provide links to some good articles.

How programs respond to events

Our program responds to external events in the following two ways:

Interrupt

Hardware input such as the operating system processing keyboard is done through interrupts, the advantage of this approach is that even if there is no multithreading, we can safely execute our code, the CPU received the interrupt signal automatically after the execution of the corresponding interrupt handler, the processing of the completion of the original code to restore the execution environment continues to execute. This approach requires hardware support and is generally encapsulated by the operating system.

Polling

The loop detects if an event has occurred, and if so, executes the appropriate handler. This is applied in the development of the bottom and the upper layer.
The Windows window program needs to write the following code in the main thread, usually called the message loop:

msg msg = {};
while (GetMessage (&msg, NULL, 0, 0))
{
  translatemessage (&msg);
  DispatchMessage (&msg);
}

The message loop constantly detects whether a message (User's UI action, System message, etc.) appears, and then distributes the message, calling the appropriate callback function for processing.
One drawback of polling is that the program cannot respond to new messages in a timely manner if it is time-consuming in the message loop of the main thread. This is evident in JavaScript, and it will be mentioned later and the solution is explored.

However, there is no such thing as a message loop code in JavaScript, we simply register the event and wait for it to be invoked. This is because the browser, node as the execution platform, has already implemented the event loop, JavaScript code does not need to intervene in the process, only to be silently waiting as the caller.

Event Loop in node

The realization of event loop through node source code

Node uses V8 as the execution engine for JavaScript while using LIBUV to implement event-driven asynchronous I/O. Its event loop uses the LIBUV default event loop.

In the src/node.cc,

environment* env = createenvironment (
    node_isolate,
    uv_default_loop (), Context
    ,
    argc,
    argv,
    exec_argc,
    exec_argv);

This code creates a node execution environment where you see the third row of Uv_default_loop (), a function in the LIBUV library that initializes the UV library itself and the default_loop_struct in it. and returns a pointer to it default_loop_ptr.
Node then loads the execution environment and completes some setup actions, and then starts the event loop:

bool more;
do {More
 = Uv_run (Env->event_loop (), uv_run_once);
 if (more = = False) {
  emitbeforeexit (env);
  Emit ' Beforeexit ' If the loop became alive either after emitting
  //event, or after running some.
  more = Uv_loop_alive (Env->event_loop ());
  if (Uv_run (Env->event_loop (), uv_run_nowait)!= 0) More
   = true;
 }
} while (more = = true);
Code = EMITEXIT (env);
Runatexit (env);
...

More is used to identify whether the next round of loops.

Env->event_loop () returns the Default_loop_ptr,uv_run function that was previously saved in the Env to start the event loop of LIBUV in the specified uv_run_once mode. In this mode, Uv_run will handle at least one event: This means that if there are no I/O events that need to be handled in the current event queue, Uv_run will block until there is an I/O event to process, or the next timer time. If there are currently no I/O events and no timer events, Uv_run returns false.

Then node will decide what to do next, based on more information:

If more is true, the next round of loop continues to run.

If more is false, it indicates that there are no waiting events, Emitbeforeexit (env), the ' Beforeexit ' event that triggers the process, examines and processes the corresponding handler function, and then jumps out of the loop immediately after completion.

Finally, the ' exit ' event is triggered, the corresponding callback function is executed, the node runs to the end, and some resource-releasing operations are followed.

In LIBUV, timer events are handled directly in the event loop, while I/O events fall into two categories:

Network I/O is the use of non-blocking I/O solutions provided by the system, such as using IOCP on Epoll,windows on Linux.

There is no (good) system solution for file operations and DNS operations, so LIBUV has built a thread pool in which to block I/O.

Alternatively, we can throw the custom function into the thread pool, and the main thread executes the callback function at the end of the run, but node does not add this functionality to JavaScript. This means that only native node is unable to open a new thread in JavaScript to execute in parallel.

The above mentioned is the entire content of this article, I hope you can enjoy.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.