Last active
June 12, 2018 06:51
-
-
Save sreepurnajasti/8115a4e5d8d155f56749684a151af767 to your computer and use it in GitHub Desktop.
simple cluster application
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
var cluster = require('cluster'); | |
var count = 0; | |
function *sendRequest(){ | |
for (var i=0; i<10000; i++) { | |
count++; | |
yield i; | |
if(count == 10){ | |
process.exit(0); | |
} | |
} | |
} | |
var gen = sendRequest(); | |
if(cluster.isMaster) { | |
var numWorkers = require('os').cpus().length; | |
console.log('Master cluster setting up ' + numWorkers + ' workers...'); | |
for(var i = 0; i < numWorkers; i++) { | |
cluster.fork(); | |
} | |
cluster.on('online', function(worker) { | |
worker.send(gen.next()); | |
worker.on('message',function(msg){ | |
console.log('Master Received msg from: '+worker.process.pid +' msg:'+ msg); | |
worker.send(gen.next()); | |
}); | |
}); | |
cluster.on('exit', function(worker, code, signal) { | |
console.log('Worker ' + worker.process.pid + ' died with code: ' + code + ', and signal: ' + signal); | |
//console.log('Starting a new worker'); | |
//cluster.fork(); | |
}); | |
} else { | |
process.on('message', function(msg){ | |
if(msg.done == true){ | |
process.exit(0); | |
}else{ | |
console.log(msg.value); | |
process.send(msg.value); | |
} | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment