Multi-process browser, multi-threaded page rendering and JS single thread

Source: Internet
Author: User
Tags border color message queue

Threads and processes

When it comes to single-threaded, you have to start with the operating system process. In earlier operating systems there was no concept of threading, a process was the smallest unit that could have resources and run independently, and was the smallest unit of program execution. Task scheduling is a time-slice rotation preemptive scheduling method, and the process is the smallest unit of task scheduling, each process has its own separate piece of memory, so that the memory address between each process is isolated from each other. Later, with the development of computer, the requirement of CPU is more and more high, the switching overhead between processes is not enough to meet the requirements of more and more complicated programs. So the thread is invented, the thread is a single sequential control flow in program execution, and is the smallest unit of program execution flow. Here the thread is likened to a workshop worker, a workshop that allows multiple workers to work together to complete a task. A process is an instance of an application that is made up of a private virtual address space, code, data, and other system resources that can request the creation and use of system resources (such as isolated memory areas, etc.) while it is running, and those resources will be destroyed as the process terminates. While the thread is an independent execution unit within the process, the process resources can be shared between different threads, so in the case of multithreading, special attention should be paid to the access control of critical resources. The main thread of the execution process starts after the system creation process, and the life cycle of the process is consistent with the life cycle of the main thread, and the exit of the main thread means that the process is terminated and destroyed. The main thread is created by the system process, and the user can create other threads autonomously, and this series of threads will run concurrently in the same process.

Cpu

CPU is the core of the computer, it is responsible for computing the computer task. Here we liken it to a factory, where the process is likened to the factory's workshop, which represents a single task that the CPU can handle. At any one time, the CPU always runs a process and the other processes are not running.

Multi-process and multi-threaded
    • Multi-process: multi-process refers to the same time, in the same computer system if two or more than two processes are allowed to be in a running state. The benefits of multi-process are obvious, such as when you can listen to a song, open the editor to hit the code, the editor and the software to listen to the process without interfering with each other.
    • Multithreading refers to a program that contains multiple execution streams, in which multiple different threads can be run concurrently to perform different tasks, that is, allowing a single program to create multiple threads of parallel execution to accomplish their tasks.
Browser multi-process architecture

Unlike many of today's multi- threaded browsers , Chrome uses multiple processes to isolate different pages. So opening a page in Chrome is a process.

When the browser was just designed, then the page is very simple, the resource share of each page is very low, so a process to handle multiple pages is feasible. And then today, a lot of pages are becoming more complex. Putting all the pages into a process browser faces challenges in robustness, responsiveness, and security. Because if the browser is in the 一个tab网页崩溃的话,将会导致其他被打开的网页应用 . In addition, compared to threads, there is no shared resource and address space between processes, so there is no security problem, and because multiple threads share the same address space and resources, there is线程之间有可能会恶意修改或者获取非授权数据等复杂的安全问题。

Note: in this case the browser should also have its own optimization mechanism, sometimes open more than one tab page, you can see in the Chrome Task Manager, some processes have been merged (such as open a number of blank tabs, you will find a number of blank tabs are merged into a process), So each tab tag corresponds to a process and is not necessarily absolute.

In addition to the browser's tab process, the browser has a number of other processes that support the process of supporting the tab page, as follows:
①browser process: The main process of the browser (responsible for coordination, master), only one. Role has

    • Responsible for browser interface display, interact with user. such as forward, retreat, etc
    • Responsible for managing each page, creating and destroying other processes
    • Management of network resources, downloads, etc.

② third-party plug-in process: each type of plug-in corresponds to a process that is created only when the plug-in is used
③GPU process: Up to one, for 3D plotting, etc.
④ Browser Rendering process (browser kernel), renderer process, internal multi-threaded, that is, each of our tabs have processes, non-impact, responsible for page rendering, script execution, event processing, etc.

Browser kernel, rendering process

The browser kernel, which is our rendering process, is known as the renderer process, which simply means that the browser kernel is an image result that can be visualized by acquiring page content, organizing information (applying CSS), computing, and combining the final output, often referred to as the rendering engine. From the above we can see that the Chrome browser enables the process individually for each tab page, so each tab page has its own instance of the render engine. The process has multiple threads underneath it, and the rendering task is done together by these ready-made tasks. So what are these threads, as follows:

1.js engine (JS kernel) thread (JS engine has multiple threads, one main thread, other background mates main thread)
Role:

    • Primarily responsible for processing JavaScript scripts, such as the V8 engine. The JavaScript engine thread is, of course, responsible for parsing JavaScript scripts and running the code.
    • Wait for the task queue task to come, and then to deal with, the browser whenever there is only one JS engine running JS Program

2.GUI Render Thread
Role:

    • Responsible for rendering the browser interface, including parsing HTML, CSS, building dom tree, render tree, layout and drawing, etc.
    • When the interface needs to be redrawn (Repaint) or because of an operation that causes reflux (reflow), the thread executes

While the JavaScript engine runs the script, the GUI render thread is in a suspended state, that is, it is "Frozen", and the GUI update is kept in a queue until the engine thread is idle and executed immediately. If the JS engine is CPU-intensive computing, then the JS engine will block, long time not idle, causing the rendering process has been unable to perform rendering, the page will appear to be stuck, rendering is not consistent, so try to avoid the JS execution time too long. If you need to perform some high-time calculations, you can open a separate webworker thread, so that no matter how dense the Webworker sub-thread calculation, how to block, will not affect the JS engine main thread, just wait for the calculation to end, The results are transferred to the main thread via PostMessage.

In addition, there is a thing called SharedWorker , and Webworker in the concept of different.

    • The webworker belongs to only one page and does not share with the renderer process of other tabs, Webworker is the process created by the renderer process.
    • Sharedworker is a JS program that is run by a single process created by the browser, which is shared by all renderer processes, and only one sharedworker process can exist in the browser.

Sharedworker is managed by the process, Webworker is a thread under a renderer process.

3. Event Trigger Thread
Role: Sounds like the execution of JS, but in fact belong to the browser, not the JS engine. Control interaction, in response to the user, when an event is triggered, the thread adds the event to the end of the queue to be processed and waits for the JS engine to process. These events can be code blocks that are currently executing, such as timed tasks, other threads that can also come from the browser kernel such as mouse clicks, Ajax asynchronous requests, and so on, but because of the single-threaded relationship of JS All these events are queued for the JS engine to process.

4.http Request Thread
Role: Ajax requests, etc., after the XMLHttpRequest is connected through the browser to open a new thread request, will detect a state change, if set with a callback function, the asynchronous thread generates a state change event is placed in the processing queue of the JavaScript engine waiting to be processed.

5. Timed Trigger Thread
Functions: SetTimeout and Setinteval, browser timer counters are not counted by the JavaScript engine, because the JavaScript engine is single-threaded, and if the state of the blocking thread affects the accuracy of the timing, Therefore, it is more reasonable to use a separate thread to timing and trigger timing.

PS:W3C's HTML standard stipulates that the low 4ms -and-middle time interval in settimeout is calculated as4ms

The onclick is handled by the DOM Binding module of the browser kernel, and when the event is triggered, the callback function is immediately added to the task queue. SetTimeout will be deferred by the timer module of the browser kernel, and the callback function will be added to the task queue when the time arrives. Ajax is handled by the Web module of the browser kernel, and the callback is added to the task queue after the network request has finished returning.

  

Keyboard, mouse I/O input and Output events, window size resize events, timers (SetTimeout, SetInterval) events, AJAX request Network I/O callbacks, etc. When these asynchronous tasks occur, they will be placed in the browser's event queue, so async is two or more than two threads of a browser. such as Ajax asynchronous requests and settimeout

JS Single Thread

JS works in the browser, is single-threaded, JS code is always executed on a thread, this thread is called the JS engine thread.

JavaScript is single-threaded, so why is JavaScript single-threaded?

This is because JavaScript is the result of the birth of the scripting language: JavaScript to handle the user interaction on the page, as well as manipulate the DOM tree, CSS style tree to give users a dynamic and rich interactive experience and server logic interactive processing. If JavaScript is multithreaded to manipulate these UI DOM, there may be conflicting UI actions, and if JavaScript is multithreaded, DOM nodes in the UI can become a critical resource under multi-threaded interaction. Assuming that there are two threads operating at the same time a DOM, one responsible for modifying a delete, then this time will need the browser to determine how to take effect which thread execution results. Of course we can solve the above problem by locking. But to avoid the greater complexity of introducing locks, JavaScript chose single-threaded execution at first.

Ps:web worker also only allows JavaScript scripts to create multiple threads, but the child threads are completely controlled by the main thread and must not manipulate the DOM.

But if a single thread, the task needs to be queued. Queuing is because of the computational capacity, CPU busy, but also forget, but a lot of time the CPU is idle, because the IO device (input) is very slow (such as the Ajax operation from the network reading data), have to wait for the results, and then down execution.

The designer of the JavaScript language realizes that at this point the main thread can completely ignore the IO device, suspend the waiting task, and first run the task that is in the queue. Wait until the IO device returns the result, and then go back and put the suspended task on hold.

Thus, all tasks can be divided into two types, one synchronization task (synchronous) and one asynchronous task (asynchronous).

Synchronization Tasks and asynchronous tasks

Synchronization task: In the main thread queued support tasks, after the completion of the previous task, after the execution of a task, the formation of an execution stack, the thread executes in the memory formation of the stack, the process of forming a heap structure, which is the structure of the memory. Execution stacks can implement layer-level calls to functions.

The asynchronous task is suspended by the main thread, not into the main thread, but into the message queue, and the callback function must be specified, and only the message queue notifies the main thread, and the execution stack is empty, the task that corresponds to the message will go to the execution stack to get execution opportunity.

Main thread

Main thread execution: "JS operating mechanism"

(1) All synchronization tasks are performed on the main thread, forming an execution stack (execution context stack).
(2) In addition to the main thread, there is a task queue. As long as the asynchronous task has a running result, an event is placed in the task queue.
(3) Once all the synchronization tasks in the "execution stack" have been executed, the system reads the "task queue" to see what events are in it. Those corresponding asynchronous tasks, so end the wait state, go to the execution stack, and start execution.
(4) The main thread constantly repeats the third step above.

Event Loops

The main thread reads events from the task queue, and the process is cyclic, so the whole mechanism is called event loop.

When the main thread runs, the heap (heap) and stack (stack) are generated, and the code in the stack calls various external APIs, which include various events (Click,load,done) in the task queue. As soon as the code in the stack finishes executing, the main thread reads the task queue and executes the callback function that corresponds to those events.

JS engine to the event queue (macro Task) and the JS Engine task (micro-task) execution exists sequentially, when each execution of an event queue time, the JS engine will detect whether there are internal non-performing tasks, if any, will be prioritized (micro-task).

The code in the execution stack (the synchronization task) is always executed before the task queue (asynchronous task) is read.

Promise

In JS, the new task Queue (promise) in ES6 is above the event loop, and the event loop checks to see if there are tasks in the ES6 task queue that are to be executed after each tick, that is, the task queue of ES6 is more prioritized than the task (event) queue in the event loop.

For example, Promise uses the ES6 task queue feature. That is, the Promise task in the task queue is performed first after the task stack is executed. Other asynchronous operations that are common above do not have a corresponding priority at the time of joining the queue.

SetTimeout (function () {console.log (' 111 ')},0);//Event Loop queue new Promise (function (resolve,reject) {   Console.log (" 2222 ");//This does not perform an asynchronous operation, performs an asynchronous operation and executes a callback function, in promise, then in the callback  resolve ();}). Then (function () {console.log (' 3333 ')})//promiseconsole.log ("44444");//main thread//output 2222 44444//above two output is synchronous operation 3333// Promise joins to queue with priority higher than settimeout 111

  

Also in nested asynchronous operations, nested async is added to the next task queue, and so on (such as nested promise)

New Promise (function (resolve,reject) {  resolve ();}). Then (function () {    console.log ("111");    return new Promise (function (resolve,reject) {   resolve ();})}). Then (function () {Console.log ("222");}) New Promise (function (resolve,reject) {    resolve ();}). Then (function () {Console.log ("33333");}) Output 33333 222
The browser's rendering process

See here, first of all, should have a certain understanding of the process and thread in the browser, then, then, then talk about the browser's browser process (control process) is how to communicate with the kernel,
Once this is understood, it is possible to concatenate this part of the knowledge and have a complete concept from beginning to end.

If you open Task Manager yourself and then open a browser, you can see that there are two processes in Task Manager (one is the master process and one is the render process that opens the tab page).
And then, under this premise, look at the whole process: (a lot easier)

      • The browser process receives the user request, first needs to obtain the page content (for example, through the network download resources), then passes the task through the Rendererhost interface to the render process
      • The renderer interface of the renderer process receives the message, simply interprets it, hands it to the render thread, and starts rendering

        • The render thread receives the request, loads the Web page, and renders the Web page, which may require the browser process to obtain resources and GPU processes to help render
        • Of course, there may be JS threads manipulating the DOM (which may cause reflow and redraw)
        • The final render process passes the result to the browser process
      • The browser process receives the results and draws the results

The rendering process of each browser core is different, we mainly focus on the following webkit .
The first is the prelude to rendering:

    1. Browser input URL, browser main process take over, open a download thread
    2. Then the HTTP request (DNS query, IP addressing, etc.) waits for the response to begin downloading the response message.
    3. Transfer the downloaded content to the renderer process management
    4. Start rendering ...

Before you say rendering, you need to understand some concepts:

    • DOM Tree: The browser speaks HTML parsing into a tree-shaped data structure.
    • CSS Rule tree: The browser parses the CSS into a tree-shaped data structure.
    • The render tree:dom tree and the CSS rule tree are merged to produce the render tree.
    • Layout: With the render Tree, the browser has been able to figure out what nodes are in the page, the CSS definitions for each node, and their dependencies, thus calculating the position of each node in the screen.
    • Painting: According to the calculated rules, through the video card, the content is drawn to the screen.
    • Reflow (reflow): When the browser found that a certain part of the changes have affected the layout, you need to go back to re-render, the insider called the process called the fallback reflow . Reflow will start recursively down from the root frame of
    • Repaint (Redraw): Changes the background color, text color, border color, and so on for an element without affecting the properties of its surroundings or interior layout, while the part of the screen is redrawn, but the geometry of the element does not change.

Note: display:none the node will not be added to the render Tree, and then it will visibility: hidden , so it will trigger display:none reflow visibility: hidden repaint .

After the browser kernel gets the response message, the rendering is roughly divided into the following steps

    1. Parses the HTML production DOM tree.
    2. Parse CSS rules.
    3. Generates a render tree from DOM tree and CSS tree.
    4. According to the layout of the render tree, it is responsible for the dimension and position calculation of each element node.
    5. Draws the render tree (painting), drawing the page pixel information.
    6. The browser sends the information from each layer to GPU,GPU, which will be composited (composite) and displayed on the screen.

Detailed steps omitted, the approximate steps are as follows, after rendering the JS engine began to execute the load event

CSS does not affect the generation of the DOM tree during loading, but it affects the generation of the render tree, which in turn affects layout, so in general, the style's link tag needs to be placed in the head as much as possible, because it is top-down when parsing the DOM tree. and CSS style is loaded by asynchronous, so that parsing the DOM tree under the body node and loading CSS style can be as parallel as possible, speed up the generation of the render tree, of course, if the CSS is added through the JS dynamic, will cause the page redraw or re-layout.
Since the HTML standard has so far (May 2017), the standard has been to stipulate that style elements should not appear in the BODY element.

The load event is mentioned earlier, so DOMContentLoaded what is the difference from the event.

    • When the domcontentloaded event is triggered, only when the DOM loading is complete, not including the style sheet, the picture. (For example, if an async-loaded script is not necessarily complete)
    • When the OnLoad event is triggered, all the DOM, stylesheets, scripts, and pictures on the page have been loaded and finished. (Render finished)

The order is:DOMContentLoaded -> load

Multi-process browser, multi-threaded page rendering and JS single thread

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.