Created
March 15, 2019 22:16
-
-
Save ivanrosolen/d108f4df7b3cceaea40cf4f85dacd28c to your computer and use it in GitHub Desktop.
NodeJS Concurrency
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 http = require('http'); | |
const cluster = require('cluster'); | |
if (cluster.isMaster) { | |
console.info('Starting...'); | |
console.info('Worker master started'); | |
const numCpus = require('os').cpus().length; | |
for (var cpu = 0; cpu < numCpus; cpu++) { | |
cluster.fork(); | |
} | |
for (var id in cluster.workers) { | |
workerEvents(cluster.workers[id]); | |
} | |
} else { | |
console.info('Starting worker ' + cluster.worker.id); | |
http.createServer((request, response) => { | |
const time = (Math.random() * 10) * 100; | |
setTimeout(() => { | |
response.end('ok'); | |
process.send({ datetime: new Date() }); | |
}, time); | |
}).listen(8000); | |
} | |
function workerEvents (worker) { | |
worker.on('message', (data) => { | |
console.log('Worker ' + worker.id + ' response ' + data.datetime); | |
}); | |
worker.on('exit', () => { | |
console.log('Worker ' + worker.id + ' exited'); | |
console.info('Starting new worker'); | |
workerEvents(cluster.fork()); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment