Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Is javascript a multithreaded language?

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces whether javascript is a multithreaded language. It is very detailed and has certain reference value. Friends who are interested must finish reading it.

Javascript is not a multithreaded language, but a single-threaded language. Javascript is a browser scripting language, and its interpreter is single-threaded; and the main purpose of JavaScript is to interact with users and operate DOM, which determines that it can only be single-threaded, otherwise it will bring complex synchronization problems.

The operating environment of this tutorial: windows7 system, javascript1.8.5 version, Dell G3 computer.

Javascript is not a multithreaded language, but a single-threaded language. The JavaScript language also does not support multithreading because the JavaScript interpreter in browsers is single-threaded.

One of the major features of the JavaScript language is single threading, that is, you can only do one thing at a time.

So why can't JavaScript have multiple threads? This will improve efficiency.

The single thread of JavaScript is related to its purpose. As a browser scripting language, the main purpose of JavaScript is to interact with users and to manipulate DOM. This determines that it can only be single-threaded, otherwise it will bring very complex synchronization problems.

In order to take advantage of the computing power of multicore CPU, HTML5 proposes the Web Worker standard, which allows JavaScript scripts to create multiple threads, but child threads are completely controlled by the main thread and cannot operate DOM. Therefore, this new standard does not change the nature of JavaScript single-threading.

Task queue

Single threading means that all tasks need to be queued and the previous task ends before the next task is executed. If the former task takes a long time, the latter task will have to wait all the time.

If the queue is because of a large amount of computation, CPU is too busy, but most of the time CPU is idle, because IO devices (input and output devices) are very slow (for example, Ajax operations read data from the network) and have to wait for the results to come out before moving on.

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

Therefore, all tasks can be divided into two types, one is synchronous task (synchronous), the other is asynchronous task (asynchronous).

A synchronous task means that a task queued on the main thread can only be executed after the previous task has been executed.

An asynchronous task refers to a task that does not enter the main thread but enters the "task queue" (task queue). Only when the "task queue" notifies the main thread that an asynchronous task can be executed.

Specifically, the operating mechanism of asynchronous execution is as follows. The same is true of synchronous execution, because it can be seen as asynchronous execution without asynchronous tasks. )

(1) all synchronization tasks are executed on the main thread, forming an execution stack (execution context stack).

(2) besides the main thread, there is a "task queue" (task queue). As long as the asynchronous task has a run result, place an event in the Task queue.

(3) once all the synchronization tasks in the execution stack are completed, the system will read the Task queue to see what events are in it. Those corresponding asynchronous tasks then end the waiting state, enter the execution stack, and begin execution.

(4) the main thread repeats the third step above.

The following figure is a schematic diagram of the main thread and task queue.

As long as the main thread is empty, it will read the "task queue", which is how JavaScript works. This process is repeated over and over again.

Event and callback function

A "task queue" is a queue of events (which can also be understood as a queue of messages). When an IO device completes a task, it adds an event to the "task queue" to indicate that the related asynchronous tasks can enter the "execution stack". The main thread reads the "task queue", which is to read what events are in it.

In addition to IO device events, the events in the Task queue also include user-generated events (such as mouse clicks, page scrolls, and so on). As long as the callback function is specified, these events will enter the "task queue" when they occur, waiting for the main thread to read.

The so-called "callback" is the code that will be linked by the main thread. An asynchronous task must specify a callback function, and when the main thread starts executing the asynchronous task, it executes the corresponding callback function.

The "task queue" is a first-in, first-out data structure, and the events in front of it are read first by the main thread. The reading process of the main thread is basically automatic, as long as the execution stack is cleared, the first event on the "task queue" automatically enters the main thread. However, due to the "timer" function mentioned later, the main thread first checks the execution time, and some events can only be returned to the main thread at a specified time.

Event Loop

The main thread reads events from the "task queue", which is a recurring process, so the whole running mechanism is also called Event Loop (event loop).

To better understand Event Loop, take a look at the following figure.

In the figure above, when the main thread is running, the heap and stack are generated, and the code in the stack calls various external API, which adds various events (click,load,done) to the "task queue". As soon as the code in the stack is finished, the main thread reads the "task queue" and executes the callback functions corresponding to those events in turn.

Execute the code in the stack (synchronous tasks), always before reading the Task queue (asynchronous tasks). Take a look at the following example.

Var req = new XMLHttpRequest (); req.open ('GET', url); req.onload = function () {}; req.onerror = function () {}; req.send ()

The req.send method in the above code is the Ajax operation to send data to the server, which is an asynchronous task, meaning that the system will not read the "task queue" until all the code in the current script has been executed. Therefore, it is equivalent to the following way of writing.

Var req = new XMLHttpRequest (); req.open ('GET', url); req.send (); req.onload = function () {}; req.onerror = function () {}

That is, the parts that specify the callback functions (onload and onerror) don't matter before or after the send () method, because they are part of the execution stack, and the system always finishes executing them before reading the "task queue."

Timer

In addition to placing events for asynchronous tasks, Task queues can also place scheduled events, that is, specifying how long some code will be executed. This is called the "timer" function, which is code that executes on a regular basis.

The timer function is mainly accomplished by two functions, setTimeout () and setInterval (). Their internal operation mechanism is exactly the same, but the difference is that the former refers to

The fixed code is executed at one time, while the latter is executed repeatedly. The following is mainly about setTimeout ().

SetTimeout () takes two arguments, the first is the callback function, and the second is the number of milliseconds to postpone execution.

Console.log (1); setTimeout (function () {console.log (2);}, 1000); console.log (3)

The result of the execution of the above code is 1pm 3pm 2, because setTimeout () delays the execution of the second line to 1000 milliseconds later.

If the second parameter of setTimeout () is set to 0, it means that the callback function specified (0 millisecond interval) will be executed immediately after the current code is executed (execution stack is cleared).

SetTimeout (function () {console.log (1);}, 0); console.log (2)

The execution result of the above code is always 2pr 1, because only after the second line is executed will the system execute the callback function in the task queue.

In short, setTimeout (fn,0) means to specify that a task executes at the earliest idle time available to the main thread, that is, as early as possible. It adds an event to the end of the Task queue, so it will not be executed until the synchronization task and the existing events of the Task queue have been processed.

The HTML5 standard specifies the minimum value (minimum interval) of the second parameter of setTimeout (), which must not be less than 4 milliseconds, which will be automatically increased if it falls below this value. Prior to this, older browsers set the minimum interval to 10 milliseconds. In addition, changes to the DOM (especially those that involve page re-rendering) are not usually performed immediately, but every 16 milliseconds. Using requestAnimationFrame () works better than setTimeout () at this point.

It is important to note that setTimeout () simply inserts the event into the "task queue" and the main thread will not execute its specified callback function until the current code (execution stack) is finished. If the current code takes a long time, it may take a long time, so there is no guarantee that the callback function will be executed at the time specified by setTimeout ().

Event Loop of Node.js

Node.js is also a single-threaded Event Loop, but its operating mechanism is different from that of a browser environment.

Please take a look at the diagram below

According to the figure above, the operation mechanism of Node.js is as follows.

(1) V8 engine parses the JavaScript script.

(2) after parsing the code, call Node API.

(3) the libuv library is responsible for the execution of Node API. It assigns different tasks to different threads, forms an Event Loop (event loop), and returns the execution result of the task to the V8 engine asynchronously.

(4) the V8 engine returns the result to the user.

In addition to setTimeout and setInterval, Node.js provides two other methods related to "task queues": process.nextTick and setImmediate. They can help us deepen our understanding of the "task queue".

The process.nextTick method can trigger a callback function at the end of the current execution stack-before the next Event Loop (the main thread reads the task queue). That is, the task it specifies always occurs before all asynchronous tasks. The setImmediate method adds an event to the end of the current "task queue", that is, the task it specifies is always executed at the next Event Loop, much like setTimeout (fn, 0). Take a look at the following example (via StackOverflow).

Process.nextTick (function A () {console.log (1); process.nextTick (function B () {console.log (2);});}); setTimeout (function timeout () {console.log ('TIMEOUT FIRED');}, 0) / / 1 TIMEOUT FIRED' / 2 TIMEOUT FIRED' / TIMEOUT FIRED

In the above code, because the callback function specified by the process.nextTick method is always triggered at the end of the current "execution stack", function An executes not only before the callback function timeout specified by setTimeout, but also function B before timeout. This means that if there are multiple process.nextTick statements, regardless of whether they are nested or not, they will all be executed on the current execution stack.

Now, look at setImmediate.

SetImmediate (function A () {console.log (1); setImmediate (function B () {console.log (2);}); setTimeout (function timeout () {console.log ('TIMEOUT FIRED');}, 0)

In the above code, setImmediate and setTimeout (fn,0) each add a callback function An and timeout, both of which are triggered by the next Event Loop. So, which callback function executes first? The answer is no. The result may be 1-TIMEOUT FIRED-2 or TIMEOUT FIRED-1-2.

Confusingly, according to the Node.js documentation, the callback function specified by setImmediate always comes before setTimeout. In fact, this only happens when recursive calls are made.

SetImmediate (function () {setImmediate (function A () {console.log (1); setImmediate (function B () {console.log (2);}); setTimeout (function timeout () {console.log ('TIMEOUT FIRED');}, 0);}); / / 1According / TIMEOUT FIRED// 2

In the above code, setImmediate and setTimeout are encapsulated in a setImmediate, and its running result is always 1-TIMEOUT FIRED-2, so function A must be triggered in front of timeout. As for row 2 after TIMEOUT FIRED (that is, function B is triggered after timeout), it is because setImmediate always registers events to the next round of Event Loop, so function An and timeout are executed in the same round of Loop, while function B is executed in the next round of Loop.

We get an important difference between process.nextTick and setImmediate: multiple process.nextTick statements are always executed at one time in the current "execution stack", while multiple setImmediate may require multiple loop to complete. In fact, this is why Node.js version 10.0 added the setImmediate method, otherwise recursive calls to process.nextTick like the following would be endless and the main thread would not read the event queue at all!

Process.nextTick (function foo () {process.nextTick (foo);})

In fact, now if you write a recursive process.nextTick,Node.js, it will throw a warning asking you to change it to setImmediate.

In addition, since the callback function specified by process.nextTick is triggered in this "event loop" and setImmediate is specified in the next "event loop", it is obvious that the former always occurs earlier than the latter and executes more efficiently (because there is no need to check the "task queue").

These are all the contents of the article "is javascript a multithreaded language?" Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report