Node single thread asynchronous non-blocking

Source: Internet
Author: User

Links: http://www.runoob.com/nodejs/nodejs-callback.html

First, what is single-threaded asynchronous non-blocking?

Single-threaded meaning the whole program starts from the beginning but using a thread, the program is executed from the top down. An asynchronous operation is a program that executes from top to bottom, but a function that executes too long does not block there until it finishes executing, and then executes the following code. Non-blocking is what this means.

Why is node asynchronous and non-blocking, with the callback function, and the timer in JS is also the classic asynchronous operation.

# # #4.1 node. js Async mechanism due to the high efficiency of asynchrony, When node. JS was designed as an efficient Web server, the author took the asynchronous mechanism and ran through the entire node. JS programming model, and the novice programmed with node. JS was often tied to the habits of other programming languages, such as C + +, Feel overwhelmed. We can peep out their differences from the following section of a simple Sleep program code, the following is a 10-time C code printed from the Linux program:

#include <time.h>#include<stdio.h>#include<unistd.h>intMain () {inti;    time_t the_time;  for(i =1; I <=Ten; i++) {the_time= Time ((time_t *)0); printf ("The time is %ld\n", the_time); Sleep (2); } exit (0);}

After compiling, the results are printed as follows:

The time is 1396492137

The time is 1396492139

The time is 1396492141

The time is 1396492143

The time is 1396492145

The time is 1396492147

The time is 1396492149

The time is 1396492151

The time is 1396492153

The time is 1396492155

From the C language printing results can be found, is printed every 2 seconds, according to the C program of the logic, the code line by row execution. The following node. JS code is intended to be like the C code above, with the purpose of printing a time interval of 2 seconds, a total of 10 prints (the programmer who first came in contact with node. js from C + + might write the following code):

function Test () {    for (var i = 0; i < i++) {        console.log ( new  Date) ;        SetTimeout (function() {}, +);    // sleep for 2 seconds before you print the next for loop     }};test ();

Printed results: Tue Apr 14:53:22 gmt+0800 (China Standard Time)
Tue Apr 14:53:22 gmt+0800 (China Standard Time)
Tue Apr 01 2014 14:53 : gmt+0800 (China Standard Time)
Tue Apr 14:53:22 gmt+0800 (China Standard Time)
Tue Apr 14:53:22 gmt+0800 (China Standard Time)
Tue A PR 14:53:22 gmt+0800 (China Standard Time)
Tue Apr 14:53:22 gmt+0800 (China Standard Time)
Tue Apr 14:53:22 gmt+0800 ( China standard Time)
Tue Apr 14:53:22 gmt+0800 (China Standard Time)
Tue Apr 14:53:22 gmt+0800 (China Standard Time)
observations found all at 14:53:22 the same Point-in-time printing, there is no sleep 2 seconds before the next round of cycle printing! Why is this? From the official documentation we see that settimeout is the second parameter that represents the callback function that executes the first argument after the elapsed time, so we can analyze it, Because of the asynchronous mechanism of node. js, after each for loop, settimeout registers a callback function that executes after 2 seconds and then immediately returns to execute Console.log (new Date), causing all the printing time to be the same point. So we modify the code for the For loop as follows:

 for (var i = 0; i < i++) {setTimeout(function() {Console.log (new  );    }

The execution results are as follows: Thu APR 09:30:35 gmt+0800 (China Standard Time)
Thu APR 09:30:35 gmt+0800 (China Standard Time)
Thu APR 09:30:35 gmt+0800 (China Standard Time)
Thu APR 09:30:35 gmt+0800 (China Standard Time)
Thu APR 09:30:35 gmt+0800 (China Standard Time)
Thu APR 09:30:35 gmt+0800 (China Standard Time)
Thu APR 09:30:35 gmt+0800 (China Standard Time)
Thu APR 09:30:35 gmt+0800 (China Standard Time)
Thu APR 09:30:35 gmt+0800 (China Standard Time)
Thu APR 09:30:35 gmt+0800 (China Standard Time) magical, still the same time point, damn! Calm down analysis, always consider the asynchronous, for loop each time settimeout registered a print time of 2 seconds after the callback function, and then immediately return, and then execute settimeout, so repeatedly until the for loop ends, because the execution speed is too fast, Causes the callback function to be executed after 10 2 seconds at the same point in time, resulting in an immediate execution of all the callback functions after 2 seconds. We add Console.log before the For loop ("before for:" + new date) and then Console.log ("After for:" + new date) to validate our speculation, The results are printed as follows (omit 8 identical print lines): Before For:thu Apr 09:42:43 gmt+0800 (China Standard Time)
After For:thu Apr 09:42:43 gmt+0800 (China Standard Time)
Thu APR 09:42:45 gmt+0800 (China Standard Time)
Thu APR 09:42:45 gmt+0800 (China Standard Time) ... (Omitting the same print line as the previous line 8) can then peek out of the node. JS asynchronous mechanism, the code in the for loop after the code in almost a unit of seconds to complete, and the callback function in the timer is required after 2 seconds to execute, but also in the same second execution completed. So how to achieve the original C language every 2 seconds to print a system time requirement function, I implemented the following a wsleep function, placed in the For loop, can achieve this purpose:

functionWsleep(Millisecond   { var= new date< Span class= "pun" > (). gettime (); while (new date (). gettime ()  <=+ Starttime) { }}    /span>                

But the function has a flaw that makes it impossible for him to use in the project, excuse me.

If there is no callback function, it becomes blocked, and the program is basically executed from top to bottom. This is mainly due to the effect of the callback function.

2. Blocking and non-blocking

node. JS callback function

The immediate manifestation of node. JS asynchronous programming is callbacks.

Asynchronous programming relies on callbacks to implement, but it cannot be said that the program is asynchronous after using the callback.

The callback function is called after the task is completed, and node uses a large number of callback functions, and all node APIs support the callback function.

For example, we can read the file while executing other commands, and after the file is read, we return the contents of the file as parameters to the callback function. This will not block or wait for file I/O operations when executing code. This greatly improves the performance of node. JS and can handle a large number of concurrent requests.

Blocking Code Instances

Create a file input.txt with the following content:

Novice Tutorial Official website address:www.  Runoob.  COM    

Create the Main.js file with the following code:

var=require("FS");  var= fs.  Readfilesync(' input.txt ');  Console.  Log(data.  ToString()); console.  Log("program execution ends!") ); 

The result of the above code execution is as follows:

$ node main.  JS Rookie Tutorial official website address:www.  Runoob.  COM program execution ends!        
Non-blocking Code instances

Create a file input.txt with the following content:

Novice Tutorial Official website address:www.  Runoob.  COM    

Create the Main.js file with the following code:

VarFs= Require("FS");Fs.ReadFile(' Input.txt ', function (Err, Data)  {if  (err return Console.err Console.< Span class= "PLN" >log (data. Tostringconsole. ( "program execution ends!"                

The result of the above code execution is as follows:

$ node main.  JS program execution end!  Novice Tutorial Official website address:www.  Runoob.  COM        

Above two examples we understand the difference between blocking and non-blocking calls. The first instance finishes executing the program after the file has been read. The second instance we do not need to wait for the file to be read, so that you can read the file while executing the next code, greatly improving the performance of the program.

As a result, blocking is performed sequentially, not blocking is not required in order, so if you need to handle the parameters of the callback function, we need to write in the callback function.

Node single thread asynchronous non-blocking

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.