Skip to content

Instantly share code, notes, and snippets.

@beatak
Created October 11, 2015 23:53
Show Gist options
  • Select an option

  • Save beatak/631ca57b61ef28f3f741 to your computer and use it in GitHub Desktop.

Select an option

Save beatak/631ca57b61ef28f3f741 to your computer and use it in GitHub Desktop.
worker example
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
var master_event = ['fork', 'online', 'listening', 'disconnect', 'exit', 'setup', 'message'];
if (cluster.isMaster) {
master_event.forEach(function(key) {
switch(key) {
case 'setup':
cluster.on(
key,
function(envish) {
console.log('on' + key + ': ' + JSON.stringify(envish));
}
);
break;
case 'fork':
case 'online':
case 'disconnect':
cluster.on(
key,
function(worker) {
console.log('on' + key + ': ' + worker.process.pid);
}
);
break;
case 'exit':
cluster.on(
key,
function(worker, something, signal) {
console.log('on' + key + ': ' + worker.process.pid + ' terminated by ' + signal);
}
);
break;
case 'message':
cluster.on(
key,
function(msg, something) {
console.log('recieved "' + msg + '"');
}
);
break;
default:
// listening
cluster.on(
key,
function() {
console.log('on' + key + ': ');
console.log(arguments);
}
);
break;
}
});
for (var i = 0; i < numCPUs; i++) {
cluster.fork();
}
Object.keys(cluster.workers).forEach(function(id) {
var time = Math.floor( Math.random() * 1000 ) + 300;
setTimeout(
function () {
cluster.workers[id].send('from Master in ' + time);
},
time
);
});
}
else {
// worker
var worker_event = ['online', 'listening', 'disconnect', 'exit', 'error', 'message'];
console.log("I am running with ID : " + process.pid );
worker_event.forEach(function (key) {
switch(key) {
case 'online':
case 'disconnect':
process.on(
key,
function() {
console.log(' WORKER: on' + key + ': ' + this.process.pid);
}
);
break;
case 'exit':
process.on(
key,
function(something, signal) {
console.log(' WORKER ' + key + ' by ' + signal);
}
);
break;
case 'message':
process.on(
key,
function(msg, something) {
console.log(' WORKER received "' + msg + '"');
}
);
break;
default:
// listening, error
process.on(
key,
function() {
console.log(' WORKER: on' + key + ': ');
console.log(arguments);
}
);
break;
}
});
var time = Math.floor(Math.random() * 1000);
setTimeout(
function() {
process.send('from worker (' + process.pid + ') messaging in ' + time);
},
time
);
// var time = Math.floor(Math.random() * 1000);
// setTimeout(
// function() {
// var msg = 'gooo: ' + time;
// console.log(msg);
// process.send(msg);
// },
// time
// );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment