Home Web Front-end JS Tutorial Node single thread realizes high concurrency principle

Node single thread realizes high concurrency principle

Feb 07, 2018 pm 01:36 PM
node principle concurrent

This article mainly introduces the principle of node single-threaded high concurrency and node asynchronous I/O. It has certain reference value. If you are interested, you can learn about it. I hope it can help everyone.

1. Principle of node single-threaded implementation of high concurrency

As we all know, nodejs is a single-threaded scripting language that supports high concurrency. But why can single-threaded nodejs support high concurrency? Many people don’t understand its principle. Let me talk about my understanding below:

1. Advantages of node: I/O-intensive processing is the strength of node, because node’s I/O requests are all asynchronous (such as: sql query request, file stream operation request, http request...)

a. What is asynchronous?

Asynchronous: Issue operation instructions, and then you can do other things. After all operations are completed, the callback is executed.

Asynchronous implementation principle:


// 第一步:定义变量
let a = 1;

// 第二步:发出指令,然后把回调函数加入异步队列(回调函数并没有执行)
setTimeout(() => {
 console.log(a);
}, 0)
// 第三步:赋值,回调函数没有执行
a = 2;
// 第四步:发出指令,然后把回调函数加入异步队列(回调函数并没有执行)
setTimeout(() => {
 console.log(a);
}, 0)
// 第五步:赋值,回调函数没有执行
a = 3;
// 当所有代码执行完毕,cpu空闲下来了,就会开始执行异步队列里面的回调函数
// 所以最后控制台输出:3 3
Copy after login

b. What is asynchronous I/O?

As the name suggests, asynchronous I/O is to issue I/O requests asynchronously

c. Although nodejs can issue I/O requests asynchronously, nodejs does not support multi-threading. Why can it support it? What about high concurrency?

Because of the I/O operation of nodejs, multi-threading is enabled at the bottom layer

When there are multiple IO requests at the same time, the main thread will create multiple eio threads to improve the efficiency of IO requests. Processing speed

Additional knowledge points:

d. Although nodejs's I/O operations enable multi-threading, all threads are started based on the main thread and can only run in one process. Unable to fully utilize cpu resources

pm2 process manager can solve this problem

pm2 is a process manager for Node applications with load balancing function.

e. cpu The relationship between the number of cores and threads

In the past single-CPU era, a single task could only execute a single program at one point in time. Later, it developed into the multi-tasking stage, where the computer can execute multiple tasks or processes in parallel at the same point in time. Although it is not the "same point in time" in the true sense, multiple tasks or processes share a CPU, and it is left to the operating system to complete the running switching of the CPU between multiple tasks, so that each task has the opportunity to obtain certain benefits. The time slice runs. Now with multi-core CPUs, multiple tasks can be executed at the same time. The specific CPU core on which the task is run depends on the design of the operating system and the CPU itself.

2 . Disadvantages of node: Not good at CPU-intensive operations

a. What are CPU-intensive operations (complex operations, image operations)


// 这就是一个cpu密集型的操作
for (let i = 0; i < 1000000; i++) {
 console.log(i);
}
Copy after login

b. Why is nodejs not good at cpu-intensive operations

Because nodejs is single-threaded

Related recommendations:

Single-threaded JS Detailed explanation of execution issues

Detailed explanation of the characteristics of JS single-threaded asynchronous io callback

Detailed introduction to some things about JavaScript single-thread (picture)

The above is the detailed content of Node single thread realizes high concurrency principle. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Analysis of the function and principle of nohup Analysis of the function and principle of nohup Mar 25, 2024 pm 03:24 PM

Analysis of the role and principle of nohup In Unix and Unix-like operating systems, nohup is a commonly used command that is used to run commands in the background. Even if the user exits the current session or closes the terminal window, the command can still continue to be executed. In this article, we will analyze the function and principle of the nohup command in detail. 1. The role of nohup: Running commands in the background: Through the nohup command, we can let long-running commands continue to execute in the background without being affected by the user exiting the terminal session. This needs to be run

Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Pi Node Teaching: What is a Pi Node? How to install and set up Pi Node? Mar 05, 2025 pm 05:57 PM

Detailed explanation and installation guide for PiNetwork nodes This article will introduce the PiNetwork ecosystem in detail - Pi nodes, a key role in the PiNetwork ecosystem, and provide complete steps for installation and configuration. After the launch of the PiNetwork blockchain test network, Pi nodes have become an important part of many pioneers actively participating in the testing, preparing for the upcoming main network release. If you don’t know PiNetwork yet, please refer to what is Picoin? What is the price for listing? Pi usage, mining and security analysis. What is PiNetwork? The PiNetwork project started in 2019 and owns its exclusive cryptocurrency Pi Coin. The project aims to create a one that everyone can participate

Application of concurrency and coroutines in Golang API design Application of concurrency and coroutines in Golang API design May 07, 2024 pm 06:51 PM

Concurrency and coroutines are used in GoAPI design for: High-performance processing: Processing multiple requests simultaneously to improve performance. Asynchronous processing: Use coroutines to process tasks (such as sending emails) asynchronously, releasing the main thread. Stream processing: Use coroutines to efficiently process data streams (such as database reads).

How can concurrency and multithreading of Java functions improve performance? How can concurrency and multithreading of Java functions improve performance? Apr 26, 2024 pm 04:15 PM

Concurrency and multithreading techniques using Java functions can improve application performance, including the following steps: Understand concurrency and multithreading concepts. Leverage Java's concurrency and multi-threading libraries such as ExecutorService and Callable. Practice cases such as multi-threaded matrix multiplication to greatly shorten execution time. Enjoy the advantages of increased application response speed and optimized processing efficiency brought by concurrency and multi-threading.

How does Java database connection handle transactions and concurrency? How does Java database connection handle transactions and concurrency? Apr 16, 2024 am 11:42 AM

Transactions ensure database data integrity, including atomicity, consistency, isolation, and durability. JDBC uses the Connection interface to provide transaction control (setAutoCommit, commit, rollback). Concurrency control mechanisms coordinate concurrent operations, using locks or optimistic/pessimistic concurrency control to achieve transaction isolation to prevent data inconsistencies.

Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Astar staking principle, income dismantling, airdrop projects and strategies & operation nanny-level strategy Jun 25, 2024 pm 07:09 PM

Table of Contents Astar Dapp Staking Principle Staking Revenue Dismantling of Potential Airdrop Projects: AlgemNeurolancheHealthreeAstar Degens DAOVeryLongSwap Staking Strategy & Operation "AstarDapp Staking" has been upgraded to the V3 version at the beginning of this year, and many adjustments have been made to the staking revenue rules. At present, the first staking cycle has ended, and the "voting" sub-cycle of the second staking cycle has just begun. To obtain the "extra reward" benefits, you need to grasp this critical stage (expected to last until June 26, with less than 5 days remaining). I will break down the Astar staking income in detail,

How to use atomic classes in Java function concurrency and multi-threading? How to use atomic classes in Java function concurrency and multi-threading? Apr 28, 2024 pm 04:12 PM

Atomic classes are thread-safe classes in Java that provide uninterruptible operations and are crucial for ensuring data integrity in concurrent environments. Java provides the following atomic classes: AtomicIntegerAtomicLongAtomicReferenceAtomicBoolean These classes provide methods for getting, setting, and comparing values ​​to ensure that the operation is atomic and will not be interrupted by threads. Atomic classes are useful when working with shared data and preventing data corruption, such as maintaining concurrent access to a shared counter.

Golang process scheduling: Optimizing concurrent execution efficiency Golang process scheduling: Optimizing concurrent execution efficiency Apr 03, 2024 pm 03:03 PM

Go process scheduling uses a cooperative algorithm. Optimization methods include: using lightweight coroutines as much as possible to reasonably allocate coroutines to avoid blocking operations and use locks and synchronization primitives.

See all articles