Home > Web Front-end > Front-end Q&A > Can node enable multi-threading?

Can node enable multi-threading?

WBOY
Release: 2022-06-15 17:06:37
Original
2971 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template