nodejs实现多线程例子
时间: 2023-10-26 10:19:19 浏览: 125
Node.js 是单线程的,但是可以通过 cluster 模块实现多进程。下面是一个简单的多进程例子:
```javascript
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
console.log(`Worker ${process.pid} started`);
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello World\n');
}).listen(8000);
console.log(`Worker ${process.pid} started listening on port 8000`);
}
```
这个例子创建了多个 worker 进程,每个 worker 进程都监听 8000 端口,当接收到请求时返回 "Hello World"。当一个 worker 进程意外退出时,主进程会重新启动一个新的 worker 进程来代替它。
阅读全文