Skip to content

Instantly share code, notes, and snippets.

@watilde
Created August 3, 2017 15:33
Show Gist options
  • Save watilde/20f6123fd541190e4bbf77cda280718c to your computer and use it in GitHub Desktop.
Save watilde/20f6123fd541190e4bbf77cda280718c to your computer and use it in GitHub Desktop.
const cluster = require('cluster');
const numCPUs = require('os').cpus().length;
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i++) cluster.fork()
for (const id in cluster.workers) {
cluster.workers[id].on('message', (data) => {
console.log(data)
cluster.workers[id].send({cmd: 'from master'})
})
}
cluster.on('exit', (worker, code, signal) => {
console.log(`worker ${worker.process.pid} died`);
})
} else {
process.on('message', (data) => {
console.log(data)
})
process.send({cmd: 'from forked'});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment