JavaScript has a concurrency model based on event loops, which are responsible for executing code, collecting and processing events, and executing subtasks in queues.

Processes and threads

Refer to the article links: www.cnblogs.com/qianqiannia…

process

The core of the computer is the CPU, which undertakes all computing tasks. The operating system is the manager of the computer, responsible for the scheduling of tasks, the allocation of resources management, the whole computer hardware; Application program is a program with some function, the program is running on the operating system.

Process is a dynamic execution process of a program in a data set. It is an independent unit of resource allocation and scheduling of the operating system. It is the carrier of application program operation.

The process is generally composed of three parts: program, data set and process control block.

Features:

  • Dynamic: a process is an execution process of a program. It is temporary and has a lifetime. It is dynamically generated and dies
  • Concurrency: Any process can execute concurrently with other processes
  • Independence: A process is an independent unit of the system for resource allocation and scheduling
  • Structure: process is composed of program, data and process control block

thread

Thread is a single sequence control flow in program execution. It is the smallest unit of program execution flow and the basic unit of processor scheduling and dispatching.

A process can have one or more threads that share the memory space of the program (that is, the memory space of the process in which it is running).

A standard thread consists of a thread ID, the current instruction pointer PC, a register, and a stack. A process consists of memory space (code, data, process space, open files) and one or more threads.

The difference between
  • A thread is the smallest unit of program execution, and a process is the smallest unit of resources allocated by the operating system.
  • A process is composed of one or more threads, threads are different execution paths within a process
  • Processes are independent of each other, but threads in the same process can share the memory space of the program and the resources of the process. Threads in one process are not visible in other processes.
  • Scheduling and switching: Thread context switching is much faster than process context switching
Relationship diagram

Why multithreading instead of multiprocessing?

Threads are cheap, start and exit faster, and have less impact on system resources. Moreover, threads share ownership of most of the core object (File Handle) with each other

If multiple processes are used, they are unpredictable and difficult to test

This article also speak well understand: www.ruanyifeng.com/blog/2013/0…

Why is JavaScript single threaded?

The single thread of JavaScript, relative to its purpose. As a browser scripting language, JavaScript’s primary purpose is to interact with users and manipulate the DOM. This means that it has to be single-threaded, which can cause complex synchronization problems. For example, if there are two threads of JavaScript at the same time, one thread adds content to a DOM node, and the other thread removes that node, which thread should the browser use?

So, to avoid complexity, JavaScript has been single-threaded since its inception, and this has been a core feature of the language and will not change.

Task queue

With a single thread, all tasks need to be queued, and the next task can be executed after the previous one has finished. If the previous task takes a long time, the later task will have to wait.

If the queue is due to a large amount of computation and the CPU is too busy, it is fine, but many times the CPU is idle because the IO devices (input and output devices) are slow (such as Ajax operations reading data from the network) and have to wait for the results to come out before executing.

The designers of the JavaScript language realized that the main thread could simply ignore the IO device, suspend the pending task and run the next one first. Wait until the IO device returns the result, then go back and continue the pending task.

Thus, tasks can be divided into synchronous and asynchronous tasks.

Synchronization tasks are queued to be executed on the main thread. The next task can be executed only after the previous task is completed.

Asynchronous tasks are tasks in the Task queue instead of the main thread. An asynchronous task is executed on the main thread only when the “task queue” notifies the main thread that it is ready to execute.

Operation mechanism:

  • All synchronization tasks are executed on the main thread, forming an execution stack (execution stack is a stack structure that stores function calls, following the principle of first in, last out).
  • In addition to the main thread, there is a “task queue”. Whenever an asynchronous task has a result, an event is placed in the “task queue”.
  • Once all synchronization tasks in the execution stack are completed, the system reads the task queue to see what events are in it. Those corresponding asynchronous tasks then end the wait state, enter the execution stack, and start executing.
  • The main thread repeats step 3 above.

Schematic diagram:

Whenever the main thread is empty, it reads the “task queue”, that’s how JavaScript works. The process repeats itself.

The console. The log (' 1 ') setTimeout (() = > {the console. The log (' 2 ')}, 500) the console. The log (' 3 ') / / execution results: / / 1 / / / 2/3Copy the code

Console. log(‘1’) indicates that the synchronous task enters the main thread for execution, and prints 1. SetTimeout () indicates that the asynchronous task enters the “task queue” and is executed after 500ms. Console. log(‘3’) is the synchronization task into the main thread execution, printing 3. After the main thread completes execution, the main thread reads setTimeout() from the “task queue” and can execute, printing 2. Results: 1, 3, 2

Event and callback functions

The “task queue” is a queue of events (also seen as a message queue). The main thread reads the “task queue” by reading the events inside it.

Task queue events include IO device events and user-generated events.

As long as the callback function is specified, these events are put into the “task queue” when they occur.

Callbacks are the ones that are suspended by the main thread.

Asynchronous tasks must have callback functions, and the main thread executing the asynchronous task executes the corresponding callback function.

Task Queue First-in, first-out sequence. If there is a timer, the main thread checks the execution time before returning to the main thread.

Event Loop

The main thread reads events from the “task queue” in a continuous Loop, so the whole operation mechanism is also called an Event Loop.

When the main thread runs, it generates heap and stack.

The code in the stack (synchronous tasks) is always executed before the “task queue” (asynchronous tasks) is read.

var req = new XMLHttpRequest();
req.open('GET', url);    
req.onload = function (){};    
req.onerror = function (){};    
req.send();
Copy the code

An Ajax request is an asynchronous task, and the event in the read “task queue” is retrieved after the current code executes. The code above is equivalent to:

var req = new XMLHttpRequest();
req.open('GET', url); 
req.send();
req.onload = function (){};    
req.onerror = function (){};
Copy the code

That is, the parts of the callback function (onload and onError) that are specified before or after send() do not matter, because they are part of the stack and are always executed before the system reads the “task queue”.

Macro and micro tasks

Refer to the article: www.cnblogs.com/wangziye/p/…

Macrotask and microtask represent two categories of asynchronous tasks.

Macro tasks are initiated by the host, while microtasks are initiated by JavaScript itself.

The relationship between macro and micro tasks

The title Macro task Micro tasks
Who initiated Host (browser, Node) Js engine
Specific events SetTimeout /setInterval 3. UI rendering/UI events 4. PostMessage, MessageChannel 5. I/O (Node. Js) MutaionObserver((HTML5 new feature) 3. Object. Observe (deprecated;ProxyObject substitution) 4. process.nexttick (node.js)
Who first run After running First run
Will it trigger a new round of tick will Don’t

Look at the following example

console.log('1')

setTimeout(function() {
    console.log('2')
    process.nextTick(function() {
        console.log('3')
    })
    new Promise(function(resolve) {
        console.log('4')
        resolve()
    }).then(function() {
        console.log('5')
    })
})

process.nextTick(function() {
    console.log('6')
})

new Promise(function(resolve) {
    console.log('7')
    resolve()
}).then(function() {
    console.log('8')
})
Copy the code

First the first macro task enters the main thread console.log(‘1’) prints: 1; SetTimeout () will be placed in the macro task queue; Process.nexttick () is placed in the microtask queue; Promise, new Promise() : 7, promise. then joins the microtask queue; The first macro task is executed, and the first micro task is executed. Process.nexttick () prints: 6; Promise.then() prints: 8; The execution of the first round of micro tasks is completed, and the second round of macro tasks is started. Console. log(‘2’) in setTimeout() prints: 2; Process.nexttick () joins the microtask queue; Promise, new Promise() : 4, promise. then joins the microtask queue; The second macro task is completed, and the second micro task process.nexttick () prints: 3; Promise.then() prints: 5. Print out: 1, 7, 6, 8, 2, 4, 3, 5.