Home > Article > Web Front-end > Can node enable multi-threading?
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.
The operating environment of this tutorial: windows10 system, nodejs version 12.19.0, Dell G3 computer.
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])
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
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
const express = require("express"), //Express框架 app = express(); // api 先关接口 app.all('/userinfo', (req, res) => { res.json({ name: '自夏', msg: '我在自夏 selfsummer' }) }) app.listen(4000, () => { console.log(`子服务启动成功`); })
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, };
Start the service. At this time, both the main service and the self-service have been started.
You can access the Express main service and sub-service addresses successfully
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 { console.log(`进程号 #${worker.id} 已断开`); }); // 意外退出进程 cluster.on('exit', (worker, code, signal) => { cluster.fork(); }); } else { // 引用Express主服务 开启主进程 require('./server') }
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)
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
You only need to change the contents of the server.js file
const http = require('http')const { pid, ppid } = require('process')const server = http.createServer((req, res) => { res.end(router(req.url))})const router = (url) => { switch (url) { case '/132': return `进程${pid} 很高兴为你服务`; case '/456': return `进程${pid} 很高兴为你服务`; default: return `没有此接口` }}server.listen(3889, () => { console.log(`Server Started in process ${pid}`);})
Still start cluster.js (multi-threaded service file)
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!