Skip to content

Instantly share code, notes, and snippets.

@stephenmathieson
Created June 26, 2013 14:58
Show Gist options
  • Save stephenmathieson/5868067 to your computer and use it in GitHub Desktop.
Save stephenmathieson/5868067 to your computer and use it in GitHub Desktop.
cluster management concept
'use strict';
var cluster = require('cluster'),
cpus = require('os').cpus().length;
function single() {
require('./worker');
}
function master() {
var nodes = cpus * 4,
workers = [];
console.log('starting %d nodes', nodes);
(function next(index) {
if (index > nodes) {
return done();
}
console.log('starting %d', index);
var worker = cluster.fork();
worker.on('message', function (msg) {
if (msg.event === 'ready') {
console.log('%d is up and running', index);
index++;
workers.push(worker);
next(index);
} else {
console.log(require('util').inspect(msg, true, 10, true))
}
});
}(1));
function done() {
console.log('started %d workers', workers.length);
}
}
if (cluster.isMaster) {
master();
} else {
single();
}
'use strict';
// worker
console.log('hi - i\'m a worker');
function wait(fn) {
setTimeout(fn, 1000);
}
wait(function () {
console.log('reading lots and lots of files');
wait(function () {
console.log('compressing stuff');
wait(function () {
console.log('building caches');
wait(function () {
console.log('ready');
process.send({
event: 'ready',
pid: process.pid
});
});
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment