A single instance of Node.js runs in a single thread. To take advantage of multi-core systems, you can use the built-in `cluster` module to create child processes that share the same server port, effectively multiplying the server's capacity.
How It Works
The cluster module allows you to create a master process that forks a number of worker processes. The master process doesn't handle application logic itself; it manages the workers. Incoming connections are distributed among the worker processes.
Example Implementation
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running`);
// Fork workers for each CPU core
for (let i = 0; i < numCPUs; i++) {
cluster.fork();
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
});
} else {
// Workers can share any TCP connection
http.createServer((req, res) => {
res.writeHead(200);
res.end('Hello from worker\n');
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
Comments
Post a Comment