Home Web Front-end JS Tutorial How nodejs handles intensive calculations

How nodejs handles intensive calculations

Apr 18, 2020 am 09:51 AM
nodejs

How nodejs handles intensive calculations

#How does nodejs handle intensive calculations?

Nodejs intensive CPU solution

First let’s talk about the advantages of nodejs single thread:

Recommended: "javascript Advanced Tutorial

High performance, compared with PHP, it avoids the overhead of frequently creating and switching threads, executes faster, and takes up less resources.

Thread safety, no need to worry about the same variable being read and written by multiple threads, causing the program to crash.

Single-threaded asynchronous and non-blocking. In fact, the underlying nodejs access I/O is still multi-threaded. Blocking/non-blocking and asynchronous/synchronization are two different concepts. Synchronization does not mean blocking, but blocking definitely does. Synchronous; it’s a bit convoluted. Please give me an example. I went to the canteen to prepare a meal. I chose Set A, and then the staff helped me prepare the meal. If I just stood aside and waited for the staff to prepare the meal for me, this situation would be This is called synchronization; if the staff is helping me prepare food, the people behind me start ordering, so that the ordering service in the entire canteen does not stop because I am waiting for set meal A. This situation is called Non-blocking. This example simply illustrates the synchronous but non-blocking situation. Furthermore, if I buy a drink while waiting for the meal to be served, and then go back to get the set meal when my number is called, my drink has already been purchased. In this way, while waiting for the meal to be served, I also perform the task of buying a drink. Calling the number is equivalent to Once the callback is executed, it is asynchronous and non-blocking. If when I buy a drink, my number has been called for me to get the set meal, but I have to wait a long time to get the drink, so I may not get set meal A until a long time after my meal number is called in the lobby, which is Single thread blocking situation.

Multi-threading:

Thread is a basic unit of CPU scheduling. A CPU can only execute one thread task.

nodejs can also perform multi-thread tasks, such as referencing the TAGG/TAGG2 module, but both tagg/tagg2 use the pthread library and the V8::Isolate class to implement the js multi-threading function. According to the rules, we Functions executed in threads cannot use the core API of nodejs, such as fs and crypto modules, so there are still great limitations.

Multiple processes:

In browsers that support HTML5, we can use webworker to throw some time-consuming calculations into the worker process for execution, so that the main process will not be blocked and the user There will be no lag feeling.

Here we need to use the child_process module of nodejs. Child_process provides the fork method, which can start a nodejs file and regard it as a worker process. After the worker completes its work, the result will be sent to the main process, and then the worker will automatically Exit, so that we can use multiple processes to solve the problem of main thread blocking.

var express = require('express');
var fork = require('child_process').fork;
var app = express();
app.get('/', function(req, res){
  var worker = fork('./work.js') //创建一个工作进程
  worker.on('message', function(m) {//接收工作进程计算结果
          if('object' === typeof m && m.type === 'fibo'){
                   worker.kill();//发送杀死进程的信号
                   res.send(m.result.toString());//将结果返回客户端
          }
  });
  worker.send({type:'fibo',num:~~req.query.n || 1});
  //发送给工作进程计算fibo的数量
});
app.listen(7878);
Copy after login

We listen to port 7878 through express. For each user request, we will fork a child process, pass the parameter n to the child process by calling the worker.send method, and at the same time listen to the message event of the message sent by the child process. , respond the result to the client.

The following is the content of the forked work.js file:

var fibo = function fibo (n) {//定义算法
   return n > 1 ? fibo(n - 1) + fibo(n - 2) : 1;
}
process.on('message', function(m) {
//接收主进程发送过来的消息
          if(typeof m === 'object' && m.type === 'fibo'){
                  var num = fibo(~~m.num);
                  //计算jibo
                  process.send({type: 'fibo',result:num})
                  //计算完毕返回结果       
          }
});
process.on('SIGHUP', function() {
        process.exit();//收到kill信息,进程退出
});
Copy after login

We first define the function fibo to calculate the Fibonacci array, and then listen to the messages sent by the main thread. The calculation is completed Then send the result to the main thread. At the same time, it also listens to the SIGHUP event of the process. When this event is triggered, the process exits.

One thing we need to note here is that the kill method of the main thread does not actually cause the child process to exit, but triggers the SIGHUP event of the child process. The real exit still relies on process.exit().

Summary:

Using the fork method of the child_process module can indeed allow us to solve the blocking problem of single-threaded CPU-intensive tasks. At the same time, it is impossible to use Node.js without the tagg package. Limitations of the core API.

Single-threaded asynchronous Node.js does not mean that it will not block. Doing too many tasks on the main thread may cause the main thread to get stuck and affect the performance of the entire program, so we must be very careful when processing a large number of tasks. For CPU-intensive tasks such as looping, string splicing, and floating-point operations, various technologies are reasonably used to assign tasks to sub-threads or sub-processes to complete, keeping the Node.js main thread open.

The use of threads/processes is not without overhead. Reducing the number of threads/processes created and destroyed as much as possible can improve the overall performance and error probability of our system.

The above is the detailed content of How nodejs handles intensive calculations. 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

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)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

The difference between nodejs and vuejs The difference between nodejs and vuejs Apr 21, 2024 am 04:17 AM

Node.js is a server-side JavaScript runtime, while Vue.js is a client-side JavaScript framework for creating interactive user interfaces. Node.js is used for server-side development, such as back-end service API development and data processing, while Vue.js is used for client-side development, such as single-page applications and responsive user interfaces.

Is nodejs a backend framework? Is nodejs a backend framework? Apr 21, 2024 am 05:09 AM

Node.js can be used as a backend framework as it offers features such as high performance, scalability, cross-platform support, rich ecosystem, and ease of development.

How to connect nodejs to mysql database How to connect nodejs to mysql database Apr 21, 2024 am 06:13 AM

To connect to a MySQL database, you need to follow these steps: Install the mysql2 driver. Use mysql2.createConnection() to create a connection object that contains the host address, port, username, password, and database name. Use connection.query() to perform queries. Finally use connection.end() to end the connection.

What is the difference between npm and npm.cmd files in the nodejs installation directory? What is the difference between npm and npm.cmd files in the nodejs installation directory? Apr 21, 2024 am 05:18 AM

There are two npm-related files in the Node.js installation directory: npm and npm.cmd. The differences are as follows: different extensions: npm is an executable file, and npm.cmd is a command window shortcut. Windows users: npm.cmd can be used from the command prompt, npm can only be run from the command line. Compatibility: npm.cmd is specific to Windows systems, npm is available cross-platform. Usage recommendations: Windows users use npm.cmd, other operating systems use npm.

What are the global variables in nodejs What are the global variables in nodejs Apr 21, 2024 am 04:54 AM

The following global variables exist in Node.js: Global object: global Core module: process, console, require Runtime environment variables: __dirname, __filename, __line, __column Constants: undefined, null, NaN, Infinity, -Infinity

Is there a big difference between nodejs and java? Is there a big difference between nodejs and java? Apr 21, 2024 am 06:12 AM

The main differences between Node.js and Java are design and features: Event-driven vs. thread-driven: Node.js is event-driven and Java is thread-driven. Single-threaded vs. multi-threaded: Node.js uses a single-threaded event loop, and Java uses a multi-threaded architecture. Runtime environment: Node.js runs on the V8 JavaScript engine, while Java runs on the JVM. Syntax: Node.js uses JavaScript syntax, while Java uses Java syntax. Purpose: Node.js is suitable for I/O-intensive tasks, while Java is suitable for large enterprise applications.

Is nodejs a back-end development language? Is nodejs a back-end development language? Apr 21, 2024 am 05:09 AM

Yes, Node.js is a backend development language. It is used for back-end development, including handling server-side business logic, managing database connections, and providing APIs.

How to deploy nodejs project to server How to deploy nodejs project to server Apr 21, 2024 am 04:40 AM

Server deployment steps for a Node.js project: Prepare the deployment environment: obtain server access, install Node.js, set up a Git repository. Build the application: Use npm run build to generate deployable code and dependencies. Upload code to the server: via Git or File Transfer Protocol. Install dependencies: SSH into the server and use npm install to install application dependencies. Start the application: Use a command such as node index.js to start the application, or use a process manager such as pm2. Configure a reverse proxy (optional): Use a reverse proxy such as Nginx or Apache to route traffic to your application

See all articles