Last active
September 11, 2021 19:46
-
-
Save mirajehossain/f35350437fb12dc0b323263358ea9c2a to your computer and use it in GitHub Desktop.
Uses of cluster module and for multicore cpu
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const cluster = require('cluster'); | |
const http = require('http'); | |
// number of cpu cores | |
const numberOfCPU = require('os').cpus().length; | |
if (cluster.isMaster) { | |
console.log(`Master is running: ${process.pid}`); | |
// Fork workers. | |
for (let i = 0; i < numberOfCPU; i++) { | |
cluster.fork(); | |
} | |
cluster.on('exit', (worker, code) => { | |
console.log(`worker ${worker.process.pid} died`); | |
// to increase the availability of the application | |
// we create new worker using fork() method if the worker is crushed. | |
// so that we can increase our applications availability. | |
if (code !== 0 && !worker.exitedAfterDisconnect) { | |
console.log(`Worker ${worker.id} crashed. \nStarting a new worker...`); | |
cluster.fork(); | |
} | |
}); | |
} else { | |
// Create a HTTP server | |
http.createServer((req, res) => { | |
res.writeHead(200); | |
res.end('hello world\n'); | |
}).listen(4000); | |
console.log(`Worker ${process.pid} started`); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment