Table of Contents
Can node enable multi-threading?
Use multiple processes
express
extensionServer.js Use express to create sub-services
serve.js First create Express multi-threaded service
cluster .js Change the Express service to a cluster
Change the Express service to the default http Service
Home Web Front-end Front-end Q&A Can node enable multi-threading?

Can node enable multi-threading?

Jun 15, 2022 pm 05:06 PM
node

Node can enable multi-threading; you can use the "child_process" module that comes with node to enable multi-threading. The syntax is "child_process.fork(modulePath[, args][, options])"; using this module can Create four types of child processes: exec, execFile, spawn, and fork.

Can node enable multi-threading?

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

Can node enable multi-threading?

Can node enable multi-threading?

We all know that Node.js runs in single-threaded mode. But it uses event-driven to handle concurrency. Based on the event-driven, non-blocking I/O model, it makes full use of the asynchronous I/O provided by the operating system for multi-task execution. It is suitable for I/O-intensive application scenarios because Asynchronous, the program does not need to block waiting for the result to be returned

The emergence of NodeJS multi-threading is not to improve concurrency, but to fully improve CPU utilization

Several ways to open multi-threading

Use the child_process module that comes with Node

child_process.fork(modulePath[, args][, options])
Copy after login

Spawn a new Node.js process and use the established IPC communication channel (which allows messages to be sent between parent and child processes) to call the specified module

cluster The cluster module can easily create child processes that share server ports. The worker process is derived using the child_process.fork() method

Can node enable multi-threading?

Use multiple processes

express

Create three new files server.js (express service) cluster.js (multi-threaded service file) extensionServer.js (express sub-service)
The following operations ensure that express is installed

npm intsall express --seve-dev

extensionServer.js Use express to create sub-services

const express = require("express"), //Express框架
app = express();

// api 先关接口
app.all('/userinfo', (req, res) => {
  res.json({ name: '自夏', msg: '我在自夏 selfsummer' })
})

app.listen(4000, () => {
 console.log(`子服务启动成功`);
})
Copy after login

serve.js First create Express multi-threaded service

const  { fork } = require("child_process"),
express = require("express"), //Express框架
app = express();

const { pid, ppid } = require('process')

// api 先关接口
app.all('/123', (req, res, next) => {
   console.log(`本次进程id为: ${pid}`);
  res.end(`本次进程id为: ${pid}`)
})

app.all('/456', (req, res, next) => {
  console.log(`本次进程id为: ${pid}`);
  res.end(`本次进程id为: ${pid}`)
})


app.listen(3888, () => {
 console.log(`服务器端启动成功 父进程 ${ppid} 当前服务进程id为 ${pid}`);
 // 开启多进程
 fork('extensionServer.js')
})

module.exports = {
  app,
  express,
};
Copy after login

Start the service. At this time, both the main service and the self-service have been started.

Can node enable multi-threading?

You can access the Express main service and sub-service addresses successfully

cluster .js Change the Express service to a cluster

Use the cluster cluster module to enable multi-threading

const os = require('os');
const cluster = require('cluster');
const { log } = console;
const express = require("express"); //Express框架

const app = express();
const processId = process.pid;

// 判断当前是否有主进程
if (cluster.isMaster)
{
	// 获取当前本机cpu核数,开启多线程
  const cpus = os.cpus().length;
  for (let i = 0; i < cpus; i++){
    cluster.fork()
  }
	//进程已断开连接	
	  cluster.on(&#39;disconnect&#39;, (worker) => {
	    console.log(`进程号 #${worker.id} 已断开`);
	  });
	// 意外退出进程
	cluster.on(&#39;exit&#39;, (worker, code, signal) => {
	      cluster.fork();
  	});


} else
{
	// 引用Express主服务 开启主进程  
  require(&#39;./server&#39;)
}
Copy after login

Start the cluster service node cluster

Of course, you can also continue to open child processes in the cluster

Interface after the second visit (one browser visit, one Postman visit)
Can node enable multi-threading?

Why are there multiple The server started successfully and the current service process id is xxx

should be the cluster module that spawns sub-processes under the current main process. Each sub-process is a new process based on all
of the main process. The processes are independent of each other. , each process has its own V8 instance and memory, and system resources are limited. It is not recommended to spawn too many child processes. The general settings are based on the system *
Number of CPU cores*

We have previously judged whether there is a main process

If there is a main process, use the cluster module to open the child process

If not, open the process

Change the Express service to the default http Service

You only need to change the contents of the server.js file

const http = require(&#39;http&#39;)const { pid, ppid } = require(&#39;process&#39;)const server = http.createServer((req, res) => {
  res.end(router(req.url))})const router = (url) => {
  switch (url)
  {
    case &#39;/132&#39;:
      return `进程${pid} 很高兴为你服务`;
    case &#39;/456&#39;:
      return `进程${pid} 很高兴为你服务`;
    default: return `没有此接口`
  }}server.listen(3889, () => {
  console.log(`Server Started in process ${pid}`);})
Copy after login

Still start cluster.js (multi-threaded service file)
Can node enable multi-threading?

Recommended study: " nodejs video tutorial

The above is the detailed content of Can node enable multi-threading?. 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)

How to use express to handle file upload in node project How to use express to handle file upload in node project Mar 28, 2023 pm 07:28 PM

How to handle file upload? The following article will introduce to you how to use express to handle file uploads in the node project. I hope it will be helpful to you!

How to delete node in nvm How to delete node in nvm Dec 29, 2022 am 10:07 AM

How to delete node with nvm: 1. Download "nvm-setup.zip" and install it on the C drive; 2. Configure environment variables and check the version number through the "nvm -v" command; 3. Use the "nvm install" command Install node; 4. Delete the installed node through the "nvm uninstall" command.

How to do Docker mirroring of Node service? Detailed explanation of extreme optimization How to do Docker mirroring of Node service? Detailed explanation of extreme optimization Oct 19, 2022 pm 07:38 PM

During this period, I was developing a HTML dynamic service that is common to all categories of Tencent documents. In order to facilitate the generation and deployment of access to various categories, and to follow the trend of cloud migration, I considered using Docker to fix service content and manage product versions in a unified manner. . This article will share the optimization experience I accumulated in the process of serving Docker for your reference.

An in-depth analysis of Node's process management tool 'pm2” An in-depth analysis of Node's process management tool 'pm2” Apr 03, 2023 pm 06:02 PM

This article will share with you Node's process management tool "pm2", and talk about why pm2 is needed, how to install and use pm2, I hope it will be helpful to everyone!

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

Let's talk about how to use pkg to package Node.js projects into executable files. Let's talk about how to use pkg to package Node.js projects into executable files. Dec 02, 2022 pm 09:06 PM

How to package nodejs executable file with pkg? The following article will introduce to you how to use pkg to package a Node project into an executable file. I hope it will be helpful to you!

What to do if npm node gyp fails What to do if npm node gyp fails Dec 29, 2022 pm 02:42 PM

npm node gyp fails because "node-gyp.js" does not match the version of "Node.js". The solution is: 1. Clear the node cache through "npm cache clean -f"; 2. Through "npm install -g n" Install the n module; 3. Install the "node v12.21.0" version through the "n v12.21.0" command.

Token-based authentication with Angular and Node Token-based authentication with Angular and Node Sep 01, 2023 pm 02:01 PM

Authentication is one of the most important parts of any web application. This tutorial discusses token-based authentication systems and how they differ from traditional login systems. By the end of this tutorial, you will see a fully working demo written in Angular and Node.js. Traditional Authentication Systems Before moving on to token-based authentication systems, let’s take a look at traditional authentication systems. The user provides their username and password in the login form and clicks Login. After making the request, authenticate the user on the backend by querying the database. If the request is valid, a session is created using the user information obtained from the database, and the session information is returned in the response header so that the session ID is stored in the browser. Provides access to applications subject to

See all articles