Skip to content

Instantly share code, notes, and snippets.

@luizcalaca
Created January 4, 2023 01:30
Show Gist options
  • Select an option

  • Save luizcalaca/b62de230ace39b6d363039a716aa07da to your computer and use it in GitHub Desktop.

Select an option

Save luizcalaca/b62de230ace39b6d363039a716aa07da to your computer and use it in GitHub Desktop.
Node.js and cluster
const express = require('express');
const app = express()
const os = require ('os')
const cluster = require ('cluster')
const numCPU = os.cpus().length
app.get('/heavy', (req, res)=> {
counter = 0;
for (let index = 0; index < 10000000000000; index++) {
counter++
}
res.status(200).json(counter)
})
if (cluster.isMaster) {
for (let index = 0; index < numCPU; index++) {
cluster.fork()
}
cluster.on('exit', (worker, code, signal) => {
console.log(`${worker.process.pid} died`);
cluster.fork()
})
}else{
app.listen(3737, () => {
console.log(`server ${process.pid}`)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment