Skip to content

Instantly share code, notes, and snippets.

@ivanrosolen
Created March 15, 2019 22:16
Show Gist options
  • Save ivanrosolen/d108f4df7b3cceaea40cf4f85dacd28c to your computer and use it in GitHub Desktop.
Save ivanrosolen/d108f4df7b3cceaea40cf4f85dacd28c to your computer and use it in GitHub Desktop.
NodeJS Concurrency
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