JavaScript single-threaded and asynchronous programming

Source: Internet
Author: User
Tags message queue hosting

Run-time Concepts

The following section explains a theoretical model. Modern JavaScript engines focus on implementing and optimizing several of the semantics described.

Visual Description

Stack

A function call forms a stack frame.

function Foo (b) {  var a = ten;   return A + B + one;} function Bar (x) {  var y = 3;   return foo (x * y);} Console.log (Bar (7));

When called bar , the first frame is created, bar and the arguments and local variables are included in the frame. When bar called foo , the second frame is created and pressed onto the first frame, and the frame contains foo the parameters and local variables. When foo returned, the topmost frame is ejected from the stack ( bar the call frame of the function is left). When it bar returns, the stack is empty.

Heap

Objects are allocated in a heap, which is used to represent a large portion of the unstructured memory area.

Queue

A JavaScript runtime contains a pending message queue. Each message has a function that is associated with this message.

At the event loop, the runtime always starts processing messages in the queue from the first message that enters the queue. Because of this, the message is moved out of the queue and called as an input parameter to the function associated with it. To use this function, calling a function always creates a new stack frame for it, as usual.

The processing of the function continues until the execution stack is empty again, and then the event loop will process the next message in the queue (if any).

Event Loops

This is called an event loop because it is often used in a way similar to the following:

 while (Queue.waitformessage ()) {  queue.processnextmessage ();}

If no messages are currently queue.waitForMessage waiting for the synchronization message to arrive.

JavaScript single-threaded and asynchronous programming Why is JavaScript a single thread?

One of the main features of the JavaScript language is single-threaded, meaning that only one thing can be done at the same time. So why can't javascript have multiple threads? This can improve the efficiency AH.

The single thread of JavaScript is related to its purpose. As a browser scripting language, JavaScript's primary purpose is to interact with the user and manipulate the DOM. This determines that it can only be single-threaded, otherwise it can lead to complex synchronization problems. For example, assuming that JavaScript has two threads at the same time, one thread adds content to one of the DOM nodes, and the other thread deletes the node, which thread should the browser take precedence over?

So, to avoid complexity, JavaScript is a single thread from birth, which has become a core feature of the language and will not change in the future.

To take advantage of the computational power of multicore CPUs, HTML5 proposes a web worker standard that allows JavaScript scripts to create multiple threads, but the child threads are completely controlled by the main thread and must not manipulate the DOM. So, this new standard does not change the nature of JavaScript single threading.

Single Thread--asynchronous

Speaking of JS single-threaded and asynchronous (asynchronous), many students can not help but think, this is not a contradiction? In fact, single-threaded and asynchronous can really not be a language feature at the same time. JS chose to become a single-threaded language, so it can not be asynchronous, but JS hosting environment (such as browser, Node) is multi-threaded, the host environment in some way (event-driven, hereinafter speaking) makes JS with asynchronous properties. Look down, you will find the JS mechanism is how simple and efficient!

Browser--Async

JS is a single-threaded language, the browser is only assigned to JS a main thread, used to perform tasks (functions), but only one task at a time, these tasks form a task queue queued for execution, but some of the front-end tasks are very time-consuming, such as network requests, timers and event monitoring, if they are to other tasks, All honestly queued for execution, the execution efficiency will be very low, even cause the page suspended animation. Therefore, the browser opens up additional threads for these time-consuming tasks, mainly including HTTP request threads, browser timed triggers, browser event-triggering threads, and these tasks are asynchronous. Describes the main thread of the browser.

Pictures from popant painting too good, can not help to lure (http://blog.csdn.net/kfanning/article/details/5768776)

Task Queue

Just said that the browser for the network request such an asynchronous task to open a separate thread, then the problem is, these asynchronous tasks are completed, the main thread how to know it? The answer is the callback function, the entire program is event-driven, each event will be bound to the corresponding callback function, for a chestnut, there is a paragraph code set a timer

SetTimeout (function() {    Console.log (time is out);},50);

When executing this code, the browser performs a timed operation asynchronously, and when the 50ms is there, it triggers a timed event, which in turn puts the callback function in the task queue. The whole program is driven by such events.
So, JS is always a single-threaded, the browser is the implementation of the guy async.

Main thread

JS has been doing a job, is to extract tasks from the task queue, put in the main thread to execute. Let's take a deeper understanding.

The picture comes from Philip Roberts's Speech "help, I'm stuck in an event-loop" very deep!
We have just understood the concept and the diagram to do a correspondence, the above mentioned in the browser for the asynchronous task of a separate thread can be understood as Webapis, the task queue mentioned above is the callback queue, we call the main thread is the part of the dotted line, The heap (heap) and stack (stack) together make up the JS main thread, the execution of the function is through the stack and out of the stack implementation, compared to a Foo () function, the main thread pushes it into the stack, in the execution of the function body, the discovery also need to execute the above several functions, so put these several functions into the stack, Wait until the function is finished, and let the function out of the stack. When the stack clears, it means that a task has been executed, and the next person task is pushed from the callback queue into the stack (the search process, called event loop, because it always loops through the queue for tasks).

A few questions that are easy to confuse
    1. What the hell is SetTimeout (f1,0)?
      The biggest question of this statement is whether F1 is executed at once. The answer is not necessarily, because to see whether the command within the main thread has been executed, the following code:

      SetTimeout (function() {Console.log (1);},0); Console.log (2);
      The output of this code is 2, 1. Since the execution of Settimeou, the anonymous function is immediately placed inside the callback queue waiting for the calling of the main thread, but this time the stack is not empty, because there is a sentence Console.log (2). After executing Console.log (2), the anonymous function is placed inside the stack via event loop. So settimeout (f1,0) This statement is not meaningless, if F1 is a time-consuming task, then you should put the task into the callback queue, wait until the main program executes.
    2. Whether the AJAX request is asynchronous
      Knowing the above, we know that the AJAX request content is asynchronous, when the request is completed, it will trigger the completion of the event, and then put the callback function into the callback queue, until the main thread executes the callback function is single-threaded.
    3. Interface rendering thread is a separate thread, is not the DOM changes, the interface is immediately re-rendering?
      If the DOM changes, the interface is immediately re-rendered, the efficiency must be very low, so the mechanism of the browser specifies that the interface rendering thread and the main thread is mutually exclusive, when the main thread executes the task, the browser render thread is in a suspended state.

How to take advantage of the browser's asynchronous mechanism

We already know that JS has been a single-threaded execution, the browser for a few obvious time-consuming tasks to open up a thread to solve time-consuming problems, but JS in addition to these obvious time-consuming problems, we can write our own program will also have time-consuming functions, this situation how to deal with it? We certainly cannot open up separate threads ourselves, but we can use the browser to open these windows to us, the browser timer thread and the event trigger thread are well utilized, and the network request thread is not suitable for us to use. Let's look at this in detail:

Assume that the time-consuming function is F1,f1 is the predecessor of the F2.

  • Triggering a thread with a timer

    function F1 (callback) {setTimeout (function() {    //  F1 code     Callback ( );},0);} F1 (F2);

    This is a high degree of coupling.

  • Triggering threads with events

    $f 1.on (' Custom ', F2);  // The binding event here is an example of jquery notation . function F1 () {setTimeout()    {///  F1 code    $f 1.trigger (' Custom ') );},0);}

    This method decouples the methods by binding custom events, so that different callback functions can be implemented by binding different events, but if you apply this method too much, it is not conducive to reading the program.

  • Publish/Subscribe

    The "events" above can be fully understood as "signals".

    We assume that there is a "signal center" in which a task executes, a signal is "released" (publish) to the signal center, and other tasks can "subscribe" to the Signal Center (subscribe) to know when they can start executing. This is called the "Publish/Subscribe Mode" (Publish-subscribe pattern), also known as the "Observer Mode" (Observer pattern).

    There are several implementations of this pattern, with Ben Alman's tiny Pub/sub, which is a plugin for jquery.

    First, F2 subscribes to "done" signals to the signal center jquery.

  • Jquery.subscribe ("Done", F2);

    The F1 then overwrites the following:

  • function F1 () {setTimeout() (function  () {  ///  F1 task code Jquery.publish (  c6> "Done"); }

    Jquery.publish ("done") means that after the completion of the F1 execution, the "Do" signal is released to the Signal center jquery, triggering the execution of the F2.

    In addition, F2 can also unsubscribe (unsubscribe) Once the execution is complete.

  • Jquery.unsubscribe ("Done", F2);
  • This method is similar in nature to "event monitoring", but is significantly better than the latter. Because we can monitor the operation of the program by looking at the message center to see how many signals exist, how many subscribers each signal has.

The benefits of Asynchrony and the right scenario
    1. Benefits of Asynchrony
      We compare synchronization and asynchrony directly with an example, assuming that there are four tasks (numbered 1,2,3,4) and that they are executed at 10ms, where Task 2 is the predecessor of Task 3 and Task 2 requires 20MS response time. Below we make a comparison, you know how to implement non-blocking I/O.

      Pictures from Soham Kaman's article
    2. The right scene
      It can be seen that when our program requires a lot of I/O operations and user requests, JS this has a single-threaded, asynchronous, event-driven multi-temperament of the language is how the occasional! It does not have to spend too much overhead and does not have to be used to handle multithreading, compared to the language of synchronous execution, where the asynchronous and event-driven mechanism of the hosting environment makes it non-blocking I/O, so you should know what kind of scene it fits into.

Reference:

Https://www.cnblogs.com/woodyblog/p/6061671.html

Http://www.ruanyifeng.com/blog/2014/10/event-loop.html

JavaScript single-threaded and asynchronous programming

Related Article

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.