search
HomeWeb Front-endJS TutorialLet's talk about the various I/O models in Node

This article will talk about the various I/O models in Node, and introduce the blocking I/O model, non-blocking I/O model and non-blocking asynchronous I/O. I hope to be helpful!

Let's talk about the various I/O models in Node

Let’s take network request IO as an example. First, we will introduce the typical process of the server processing a complete network IO request:

Lets talk about the various I/O models in Node

The application obtains the result of an operation, which usually includes two different stages:

  • Waiting for the data to be ready

  • Copying data from the kernel to the process

Below, we take the recvfrom function as an example to explain various IO models

Blocking I/O Model (blocking I/O)

Blocking call means that before the call result is returned, the current thread will be suspended, and the calling thread can only wait for all operations at the system kernel level The call will not end until it is completed.

Blocking I/O causes the CPU to wait for I/O and wastes CPU time slices.

Lets talk about the various I/O models in Node

Non-blocking I/O model (non-blocking I/O)

Compared with the former, non-blocking I/O Return directly without data. To obtain the data, you need to try to read the data again through the file descriptor

Lets talk about the various I/O models in Node

Non-Blocking callGet returned ( Not the actual expected data), the CPU time slice can be used to process other things, which can significantly improve performance.

But the problem that comes with it is that the previous operation was not a complete I/O, and the returned result was not the expected business data, but only the asynchronous call status.

In order to obtain complete data, the application needs to repeatedly call the IO operation to confirm whether the operation has been completed. This operation is called Polling. Several common polling strategies are as follows

Busy Polling

This is the most primitive and lowest performance way. It checks the I/O status through repeated calls to obtain complete data

Lets talk about the various I/O models in Node

Advantages: Simple programming

Disadvantages: The CPU is always consumed in polling, which also affects server performance, because the server still has to respond after you poll

I/O multiplexing model (I/O multiplexing)

Lets talk about the various I/O models in Node

In the I/O multiplexing model, it will be used Select or Poll function or Epoll function (supported by the kernel after Linux 2.6), these two functions will also cause the process to block, but they are different from blocking I/O.

These three functions can block multiple I/O operations at the same time, and can detect the I/O functions of multiple read operations and multiple write operations at the same time until data is readable or writable. , the I/O operation function is actually called.

The differences between the three I/O multiplexing mechanisms are as follows

  • select

Due to select A 1024-length array is used to store file status, so up to 1024 file descriptors can be detected simultaneously

  • poll

Slightly improved compared to select. The use of linked lists avoids the length limit of 1024 and avoids unnecessary traversal checks. The performance is slightly improved compared to select.

  • ##epoll/ kqueue

is the most efficient I/O event notification mechanism under Linux. If no I/O event is detected during polling, it will

sleep, until the event occurs and the thread is awakened. It truly utilizes event notifications and executes callbacks instead of traversing (file descriptor) queries, so it does not waste CPU

Lets talk about the various I/O models in Node

Summary: Essentially,

Polling is still a synchronous operation because the application is still waiting for the I/O to return completely. During the waiting period, it either traverses the file description state or sleeps to wait for the event to occur.

Signal-driven I/O model

Lets talk about the various I/O models in NodeIn the signal-driven I/O model In , the application uses signals to drive I/O and installs a signal processing function. The process continues to run without blocking.

When the data is ready, the program will receive a SIGIO signal and can call the I/O operation function in the signal processing function to process the data.

Summary: So far, the signal-driven I/O model is more in line with our asynchronous needs. The program will execute other business logic asynchronously while waiting for data.

but! ! ! It is still blocked during the process of copying data from the kernel to user space, which is not a complete revolution (asynchronous).

Ideal (Node) non-blocking asynchronous I/O

Our ideal asynchronous I/O should be a non-blocking call initiated by the application, without the need to obtain data through polling , there is no need to wait needlessly during the data copy phase, but after the I/O is completed, it can be passed to the application through a signal or callback function, during which the application can execute other business logic.

Lets talk about the various I/O models in Node

Actual asynchronous I/O

In fact, the Linux platform natively supports asynchronous I/O (AIO), but currently AIO is not perfect. , so when implementing high-concurrency network programming under Linux, the I/O multiplexing model is mainly used.

Under Windows, true asynchronous I/O is implemented through IOCP.

Multi-threaded simulation of asynchronous I/O

Under the Linux platform, Node uses the thread pool to allow some threads to perform blocking I/O or non-blocking I/O rounds Data acquisition is completed by querying, allowing a separate thread to perform calculations, and passing the I/O results through communication between threads, thus realizing the simulation of asynchronous I/O.

In fact, the bottom layer of the IOCP asynchronous asynchronous solution under the Windows platform is also implemented using a thread pool. The difference is that the latter thread pool is hosted by the system kernel.

We often say that Node is single-threaded, but in fact it can only be said that JS is executed in a single thread, whether it is *nix or windows platform , the bottom layer uses the thread pool to complete I/O operations.

For more node-related knowledge, please visit: nodejs tutorial!

The above is the detailed content of Let's talk about the various I/O models in Node. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.