The relationship between CPU, process, and thread

  • The CPU is the core of the computer and does all of the computer’s work

  • The minimum unit of CPU resources allocated to a process

  • The smallest unit of thread CPU scheduling

The relationship between the three is described in the previous article as a factory, and the factory is the CPU.

The factory can only supply power to one workshop at a time, which means that when one workshop is working, all the other workshops cannot work.

This means that a CPU can only run one task at a time, and processes are workshops. The CPU can only process one process at a time, and the other processes enter a non-running state.

There are many workers in each workshop, and these workers share a workshop.

This is equivalent to a process can have multiple threads, and multiple threads share the resources of the process.

Browsers are multi-process

The browser is multi-process, you can open task manager, in the process to see the Chrome browser (or any browser open multiple TAB pages) :

Browser Process classification

  • The Browser process
    • The main browser process that coordinates control of other child processes
  • Third-party plug-in processes
    • Each plug-in used is equivalent to a process that is created only when the plug-in is used
  • GPU process
    • One at most for 3D drawing
  • Browser renderer (kernel)
    • By default, each Tab page has one process and does not affect each other
    • Controls page rendering, script execution, event handling, etc

Browser renderer (kernel)

Of course there are multiple threads in the renderer process, let’s take a look:

  • The GUI thread
    • Responsible for rendering browser interface, parsing HTML, CSS.
    • This thread executes when the page is redrawn or when a backflow is triggered
    • This thread and the JS engine thread are mutually exclusive and cannot run at the same time
  • JS engine thread
    • Responsible for JS scripts
    • There is only one JS engine thread
    • Again, it is mutually exclusive with GUI threads
  • Event trigger thread
    • Used to control the event loop
    • When the JS engine executes the code, the corresponding task is added to the event-firing thread
    • When a corresponding event is triggered, the thread adds the event to the end of the task queue and waits for a response
  • Timed trigger thread
    • The thread of setInterval() and setTimeout()
    • Scheduled tasks are not counted by the JS engine
  • Asynchronous HTTP request threads
    • The browser has a separate thread for handling Ajax requests

The GUI rendering thread and the JS engine thread are mutually exclusive: since JS can manipulate the DOM, if you render the page while modifying the attributes of these elements, the element data may be inconsistent before and after rendering. So to prevent unexpected results from rendering, the browser makes them mutually exclusive.

Event Loop

What is an Event loop

  • Js is divided into synchronous tasks and asynchronous tasks

  • Synchronization tasks are executed on the JS engine thread, forming an execution stack

  • The event-triggered thread manages a task queue

    • Timed trigger threadIs itself a synchronous task, but the callback function is an asynchronous task, soJs engine threadWill informTimer trigger threadwhenTimer trigger threadAfter the message is received, the callback function is placed into theTask queuein
    • In the same way,Asynchronous HTTP request threadsWill receive a fromJs engine threadNotification to send a network request whenAsynchronous HTTP request threadsAfter receiving the message, the callback function is put in after the request is successfulTask queuein
  • When the synchronous tasks in the execution stack are completed and the JS engine thread is idle, the system automatically identifies the task queue and adds the asynchronous tasks that can be run to the execution stack.

To illustrate this, it might be clearer:

Macro and micro tasks

Both micro tasks and macro tasks are asynchronous tasks, which belong to the same queue. The main differences lie in their execution sequence and the direction and value of Event Loop.

What is a macro task

The GUI rendering thread and JS engine thread are mutually exclusive. To keep macro tasks and DOM tasks in order, the browser renders the page after one macro task and before the next.

The macro tasks are:

  • Overall code script
  • setInterval()
  • setTImeout()
  • .

What are microtasks

Microtasks can be understood as tasks that are executed immediately after macro tasks are executed, that is, after macro tasks are executed, all microtasks are executed before page rendering.

Microtasks include:

  • The original Promise
  • process.nextTick
  • .

How to distinguish macro tasks from microtasks

  • Macro tasks are provided by the JS host

    • At present, the more common hosts areThe browserandnode
  • Microtasks are provided by the language standard (JS itself)

    • Javascript is standardized by ECMA, so language standards provide microtasks, such as those provided in ES6Promise

To sum up, setTimeout is provided by the host and Promise is provided by ES6, so promises are executed earlier than setTimeout timers.

chestnuts

1.

console.log(1)

Promise.resolve().then((a)= > {
  console.log(2)})console.log(3)  // The output is 1, 3, and 2
Copy the code
  • becausePromiseIn thethenMethod is called asynchronously, so 2 is executed last.

2,

console.log(1)

setTimeout((a)= > {
  console.log(2)},0);

new Promise((resolve, reject) = > {
  console.log(3)
  resolve()
}).then((a)= > {
  console.log(4)})console.log(5) // Output results: 1, 3, 5, 4, 2
Copy the code
  • Perform the synchronization tasks in sequence. The result is 1

  • When a setTimeout is encountered, it is pushed into the event queue and is a macro task

  • When you encounter a Promise, you directly execute output code 3, placing the then method’s callback function on the microtask event queue

  • To execute the synchronization task, 5 is displayed

  • After the implementation of the first round, check the micro task, you can output 4

  • The second round starts with the macro task and outputs 2

3,

console.log(1)

new Promise((resolve, reject) = > {
  console.log(2)
  setTimeout((a)= > {
    console.log(3)},0);
  resolve()
}).then((a)= > {
  console.log(4)
})

setTimeout((a)= > {
  console.log(5)
  new Promise((resolve, reject) = > {
    console.log(6)
    resolve()
  }).then((a)= > {
    console.log(7)})},0);

console.log(8) // Output results: 1, 2, 8, 4, 3, 5, 6, 7
Copy the code
  • Execute synchronization tasks in sequence, and output 1
  • encounterPromise, direct output2That will beSetTimeout (1)pushMacro taskEvent queue, and put the then method callback function intoMicro tasksEvent queue
  • encounterSetTimeout (2)And push it intoMacro taskTo the event queue
  • After the synchronization task is executed, 8 is displayed
  • Round one is complete. FoundMicro tasksAnd the output4
  • In the second round, execute firstMacro task.SetTimeout (1)The output3
  • See noMicro tasks, that is, the outputMacro task.SetTimeout (2)The output5
  • SetTimeOut (2)There arePromiseDirectly execute the output6And willthenMethod callback function intoMicro tasksIn the
  • performMicro tasksAnd the output7

conclusion

Let’s sum it up with a picture

Note: this article is my notes in the learning process, if there are mistakes or inaccuracies, please give me more advice ~