Home  >  Article  >  Web Front-end  >  Is nodejs single-process?

Is nodejs single-process?

青灯夜游
青灯夜游Original
2021-11-11 16:19:362105browse

nodejs is a single process. Node follows a single-threaded single-process model, but it is based on event-driven, asynchronous non-blocking mode, which can be applied to high-concurrency scenarios and avoids the resource overhead caused by thread creation and context switching between threads.

Is nodejs single-process?

The operating environment of this tutorial: windows7 system, nodejs version 12.19.0, Dell G3 computer.

Process

Process is a running activity of a program in the computer on a certain data collection. It is the basic unit for resource allocation and scheduling in the system. It is the basis of the operating system structure, and the process is the container of threads (from encyclopedia). A process is the smallest unit of resource allocation. When we start a service and run an instance, we open a service process. For example, the JVM in Java itself is a process. In Node.js, a service process is opened through node app.js. Multi-process is a copy (fork) of the process. Fork Each process that comes out has its own independent space address and data stack. One process cannot access variables and data structures defined in another process. Only when IPC communication is established can data be shared between processes.

Thread

Thread is the smallest unit that the operating system can perform calculation scheduling. First of all, we must understand that threads belong to the process and are included in the process. A thread can only belong to one process, but a process can have multiple threads. Single thread Single thread means that a process only opens one thread. Javascript is single-threaded. The programs are executed sequentially (JS asynchronous is not mentioned here for the time being). You can imagine a queue. After the previous one is executed, the next one can be executed. When you use single thread When coding in threading language, do not have too many time-consuming synchronization operations, otherwise the thread will be blocked and subsequent responses cannot be processed. If you use Javascript for coding, please take advantage of the asynchronous operation features of Javascript as much as possible.

nodejs single process single thread event driver

Node follows the single thread single process model. The single thread of node means that the js engine has only one instance, and It is executed in the main thread of nodejs, and node handles asynchronous operations such as IO in an event-driven manner. The single-threaded mode of node only maintains one main thread, which greatly reduces the cost of switching between threads, but there will be multiple worker threads for performing asynchronous operations.

However, the single thread of node prevents CPU-intensive operations from being performed on the main thread, otherwise the main thread will be blocked. For CPU-intensive operations, independent child processes can be created in node through child_process. The parent-child process communicates through IPC. The child process can be an external application or a node subprogram. After the child process is executed, the results can be returned to the parent process.

Node.js operating mechanism

  • The V8 engine parses JavaScript scripts.
  • The parsed code calls the Node API.
  • The libuv library is responsible for the execution of the Node API. It allocates different tasks to different worker threads to form an Event Loop, and returns the execution results of the tasks to the V8 engine in an asynchronous manner.
  • The V8 engine returns the results to the user.

This picture is the operating principle of the entire Node.js. From left to right, from top to bottom, Node.js is divided into four layers, namely the application layer, V8 engine layer, Node API layer and LIBUV layer.

  • Application layer: That is, the JavaScript interaction layer, the most common ones are Node.js modules, such as http, fs
  • V8 engine layer: That is, the V8 engine is used to parse JavaScript syntax, and then Interacting with the lower-layer API
  • NodeAPI layer: Provides system calls for the upper-layer module, usually implemented in C language, to interact with the operating system.
  • LIBUV layer: It is a cross-platform bottom-level encapsulation that implements event loops, file operations, etc. It is the core of Node.js's asynchronous implementation

Node.js event loop

Node.js is usually single-process.

  • The main thread runs V8 and Javascript
  • Multiple sub-threads are scheduled through the event loop

Event loop:

The event loop is a programming construct used to wait for and dispatch events or messages in the program. The main thread reads events from the "task queue". This process is continuous, so the entire running mechanism is Called Event Loop (event loop)

Event Queue:

When the user's network request or other asynchronous operation arrives, the node will put it in the Event Queue Among them, it will not be executed immediately at this time, and the code will not be blocked. It will continue until the main thread code is executed.

Task queue:

Task queue "is an event queue (can also be understood as a message queue). When the IO device completes a task, it is in the "task" Adding an event to the "queue" means that the relevant asynchronous tasks can enter the "execution stack". The main thread reads the "task queue", which is to read the events in it.

Event-driven:

The essence is to run the program through the main loop plus event triggering
node
Node.js is not a language or a framework. It is just a JavaScript runtime environment based on the Google V8 engine, which is an expansion of js functions. . Provides network, file, dns resolution, process thread and other functions.

libuv
libuv is a package library specially developed for Node.js, providing cross-platform asynchronous I/O capabilities.

Note:

  • An event loop has one or more task queues. A task queue is a group of tasks

  • Libuv mainly uses the event-driven module provided by the system to solve network asynchronous IO, and uses the thread pool to solve file IO. In addition, a timer is implemented to encapsulate the use of processes, threads, etc.

In fact, the event loop here is the same as the event loop of js in the browser. The main thread allows synchronous code, and the asynchronous code is executed in the corresponding worker thread. After the callback execution result Put it into the event queue and wait for the main thread to execute the tasks of the event queue.

Event-driven event loop to achieve high concurrency

Specific execution sequence:

1. Each Node.js process has only one main thread executing the program The code forms an execution context stack

2. In addition to the main thread, an "Event queue" is also maintained. When the user's network request or other asynchronous operation arrives, node will put it into the Event Queue. At this time, it will not be executed immediately, and the code will not be blocked. It will continue until the main thread code is executed. complete.

3. After the execution of the main thread code is completed, then through the Event Loop, which is the event loop mechanism, start to take out the first event from the beginning of the Event Queue, and allocate a thread from the thread pool to execute this event. , then continue to take out the second event, and then allocate a thread from the thread pool to execute, then the third, and the fourth. The main thread continuously checks whether there are unexecuted events in the event queue until all events in the event queue have been executed. After that, whenever a new event is added to the event queue, the main thread will be notified to take them out in order and hand them over to EventLoop for processing. When an event is executed, the main thread will be notified, the main thread will execute the callback, and the thread will be returned to the thread pool.

Note

The node.js single thread we see is just a js main thread sharing a thread with UI rendering. The essential asynchronous operation is still performed by the thread pool Completed, node hands over all blocking operations to the internal thread pool for implementation. It is only responsible for continuous round-trip scheduling and does not perform real I/O operations, thereby achieving asynchronous non-blocking I/O. This is The essence of node's single-threading and event-driven.

Summary:

1. The libuv thread pool opens 4 threads by default and can open up to 128 threads. (For example: In the past, the web server could only receive up to 100 requests at the same time. If there were too many, it would be unable to receive and the server would hang up. The so-called high concurrency of nodejs means that it can receive 1,000 or 10,000 requests at the same time. It's just waiting in a queue.)

2. The main thread executes js, which is single-threaded. The js code is doing a lot of calculations and is CPU intensive. If the main thread is not free, it cannot handle IO matters, so it will be blocked.

3. Callbacks can only ensure that a certain request is executed in order, but cannot guarantee the order in which multiple requests access a resource. Multiple requests need to be locked when accessing a resource. Just use transaction locking.

[Recommended learning: "nodejs tutorial"]

The above is the detailed content of Is nodejs single-process?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn