Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save AJamesPhillips/9fa3002909b7eda0b113667beb285acf to your computer and use it in GitHub Desktop.
Save AJamesPhillips/9fa3002909b7eda0b113667beb285acf to your computer and use it in GitHub Desktop.
Using multiple cores on node
// Adapted from: https://nodejs.org/docs/latest/api/cluster.html
const cluster = require('cluster');
const http = require('http');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
console.log(`Master ${process.pid} is running on ${numCPUs} numCPUs`);
// 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) => {
console.log(`hello world from: ${process.pid}\n`);
res.writeHead(200);
res.end(`hello world from: ${process.pid}\n`);
}).listen(8000);
console.log(`Worker ${process.pid} started`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment