Nodejs Event Polling Details

Source: Internet
Author: User
Tags readfile

Directory

    • Overview
    • Nodejs Features
    • Event polling
    • About Async methods

Overview

About Nodejs the introduction of online information is very much, recently because in the collation of some functional programming information, many times encountered Nodejs related content. So I'm going to write an article to summarize the knowledge of Nodejs, including "What does it mean by a single thread", "what non-blocking refers to", and, most importantly, its implementation mechanism of "event polling".

This article does not introduce the advantages and disadvantages of Nodejs (where applicable), how the NODEJS environment is built, and the use of some nodejs libraries, and other basic knowledge.

Nodejs features

Any on-line introduction of NODEJS will refer to the Nodejs two main features: single-threaded, non-blocking. But as far as I know, most of the introductions are around, and there is no detailed, systematic explanation of what is going on. Here I will do my best to explain in detail my understanding of the above two.

Non-blocking

Let's take a look first. The code for asynchronous programming in net:

using (FileStream fs = new FileStream ("Hello.txt", FileMode.Open))
{
byte[] data = new BYTE[FS. Length];
Fs. BeginRead (data, 0, FS. Length, New AsyncCallback (OnRead), null);
Console.WriteLine ("The End");
}

As shown in the code above, Because Filestream.beginread is an asynchronous method, the call to the Filestream.beginread method does not block the calling thread, regardless of how large the Hello.txt file is, and the Console.WriteLine method executes immediately. Similarly, if all the methods in Nodejs are "async methods", then the call of any method in Nodejs will not block the calling thread, in essence, most of the library methods in Nodejs are indeed the case. This is why we would say that the code in Nodejs is non-blocking.

Single Thread

There are many people who misunderstand this concept, thinking that Nodejs is a thread in the program, and then a lot of people ask: since there is only one thread, how do you handle multiple tasks in parallel?

In fact, the single thread here is not referring to the existence of a Nodejs program, I personally feel that the official "single-threaded" argument itself is misleading, so it is no wonder that the majority of beginners. So what does "single thread" mean? In fact, "single-threaded" here refers to the code we (developers) can only run in one thread (which can be called the mainline), as we do in the Windows Desktop Program development, and all the interface code that we write is running in the UI thread.

So that's just the problem, all the code written is running in a thread, so how do you go about parallel processing tasks? This is going to come up with the "async method" described earlier, yes, although all the code developers write is running in a thread, but we can call the Async method in this thread, and the asynchronous method internal implementation of course to adopt multithreading. Just like:

As shown, the single thread in the Nodejs refers to the main thread in the diagram, which contains a looping structure that keeps the entire program running.

Note: This loop structure is also known as the "pump" structure, which is the necessary structure for each system. See my previous blog, "Source of power: Pumps in code."

So we can say that the code written in Nodejs (including the callback method) runs only on one thread, but does not mean that it has only one thread. Many asynchronous methods in Nodejs are implemented internally using multithreading mechanisms (as described later).

Event polling

If some of the readers of my previous blog may know that a system (or a program) must contain at least one large loop structure (which I call "pump"), it is a prerequisite for sustaining the system's continued operation. The same structure is included in Nodejs, which we call "event polling", which exists in the main thread and is responsible for constantly invoking code written by the developer. We can check the instructions on Nodejs on the official website of Nodejs:

As we can see, this "looping" structure in Nodejs is not visible to the developer.

So how do developers write code that gets called through event polling? Especially some of the callback functions in asynchronous methods? Take a look at the following picture:

As shown, after each asynchronous function execution finishes, an event is appended to the event queue (with some necessary parameters saved). The event polls the next loop to take out the event, and then invokes the callback function (parameter) for the Async method. This allows Nodejs to ensure that each line of code written by the developer (each callback) is executed in the main thread. Note that there is a problem, if the developer calls the blocking method in the callback function, then the whole event polling is blocked and events in the event queue are not processed in time. Because of this, some of the library methods in Nodejs are asynchronous and encourage users to invoke asynchronous methods.

In fact, when you see this, if you have a better understanding of Windows programming (especially for Windows interface programming), you may already think of the Windows message loop.

Yes, the event polling principle in Nodejs is similar to the principle of Windows message loops. The code written by the developer runs in the main thread, and if you write a blocking code, in the Windows desktop program, the interface will get stuck because the message is not processed in time.

Let's take a look at the following Nodejs code:

var fs = require (' FS ');
Fs.readfile (' Hello.txt ', function (err, data) {//Read files asynchronously
Console.log ("Read file End");
});
while (1)
{
Console.log ("Call readFile over");
}

As above, although we use asynchronous methods to read the file, the "Read file end" will never output after the file has been read, meaning that the callback function of the ReadFile method will not execute. The reason is simple because the subsequent while loop does not exit, causing the next event poll not to start, so the callback function cannot execute (including all other callbacks). The fact is that all the code that developers write can only run on the same thread (let's call it the mainline).

About Async methods

The so-called asynchronous method is that calling the method does not block the calling thread, even if the method internally takes time-consuming action. You can understand that a new thread has been created for the method internally to handle the task, whereas invoking the Async method simply opens the new thread. The following code simulates the internal structure of an async method (just the simulation, not the actual):

public void dosomething (int arg1,asynccallback callback)
{
(Action) (Delegate ()
{
Thread.Sleep (1000*20); Simulate time-consuming operations
if (callback! = NULL)
{
Callback (...); Call callback function
}
}). BeginInvoke (Null,null);

}

As shown in the code above, calling the DoSomething method does not block the calling thread. So for each asynchronous method, how to determine whether the asynchronous operation is complete? The asynchronous method must be passed a callback function as a parameter, in. NET, which is typically of type AsyncCallback. As everyone knows, Filestream.beginread/beginwrite and Socket.beginreceive/beginsend are among the methods.

However, the reason I want to mention async methods is to let you distinguish between asynchronous methods in Nodejs and. NET is a significant difference between asynchronous methods, although the internal principles can be understood as consistent, but in the invocation of the callback function of this point, the two have a different way.

In. NET, the callback function for each async method executes in another thread (not the calling thread), and in Nodejs, the callback function for each async method still executes on the calling thread. As for why, you can take a look at the section of the previous event polling, each callback function in Nodejs is called by an event poll in the main thread. This ensures that in Nodejs, any code written by the developer is run in the same thread (so-called single-threaded).

Note: Do not understand the calling thread, the current thread is what the students can look at this blog: "Strategically advantageous position: carding programming conventions."

Nodejs Event Polling Details

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.