Skip to content

Instantly share code, notes, and snippets.

@sdaoudi
Created November 22, 2021 07:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdaoudi/b15ed0f31e62c899a380a11f2383e4b8 to your computer and use it in GitHub Desktop.
Save sdaoudi/b15ed0f31e62c899a380a11f2383e4b8 to your computer and use it in GitHub Desktop.
Example of node cluster
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 (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
// In this case it is an HTTP server
http.createServer((req, res) => {
res.writeHead(200);
res.end(`hello world - response from ${process.pid} Worker\n`);
}).listen(8080);
console.log(`Worker ${process.pid} started`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment