Node runs in a single thread, using a single-threaded asynchronous non-blocking mode; but strictly speaking, there are multiple threads in the node. Single-thread means that there is only one js engine in the node running on the main thread, and the others Asynchronous operations are also executed by independent threads. At the same time, node is single-threaded by default, and a "node.js" cannot utilize multi-core resources.
The operating environment of this tutorial: windows10 system, nodejs version 12.19.0, Dell G3 computer.
Node is run in a single thread, using single-thread asynchronous non-blocking mode.
When it comes to node, we can immediately think of words such as single-threaded, asynchronous IO, and event-driven. The first thing to clarify is whether node is really single-threaded. If it is single-threaded, then where are asynchronous IO and scheduled events (setTimeout, setInterval, etc.) executed.
Actually, strictly speaking, node is not single-threaded. There are many kinds of threads in node, including:
js engine execution thread
Timer thread (setTimeout, setInterval)
Asynchronous http thread (ajax)
What we usually call single thread means that there is only one js engine in node running on the main thread. Other asynchronous IO and event-driven related threads use libuv to implement internal thread pools and thread scheduling. There is an Event Loop in libv, and switching through Event Loop can achieve an effect similar to multi-threading. Simply put, Event Loop maintains an execution stack and an event queue. If asynchronous IO and timer functions are found in the current execution stack, these asynchronous callback functions will be put into the event queue. After the execution of the current execution stack is completed, the asynchronous callback functions in the event queue are executed in a certain order from the event queue.
In the above figure, from the execution stack to the event queue, and finally the callback function is executed in a certain order in the event queue, the whole process is a simplified version of Event Loop. In addition, when the callback function is executed, an execution stack will also be generated. Asynchronous functions may be nested inside the callback function, which means that the execution stack is nested.
In other words, the single thread in node means that the js engine only runs on the only main thread. Other asynchronous operations also have independent threads to execute. Through libv's Event Loop, a similar multi-thread is implemented. Thread context switching and thread pool scheduling. Threads are the smallest processes, so node is also a single process. This explains why node is single-threaded and single-process.
Recommended learning: "nodejs video tutorial"
The above is the detailed content of Does node all run single-threaded?. For more information, please follow other related articles on the PHP Chinese website!