Skip to content

Instantly share code, notes, and snippets.

@jclulow
Forked from ry/fib.js
Created March 12, 2012 00:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jclulow/2018973 to your computer and use it in GitHub Desktop.
Save jclulow/2018973 to your computer and use it in GitHub Desktop.
a proper fibonacci server in node. it will light up all your cores.
var os = require('os');
var http = require('http')
var fork = require('child_process').fork;
function fib(n) {
if (n < 2) {
return 1;
} else {
return fib(n - 2) + fib(n - 1);
}
}
if (process.argv[2] == 'fib') {
process.on('message', function(m) {
process.send({ result: fib(m.input) });
});
} else {
var busyChildren = 0;
var freeChildren = [];
var reqQueue = [];
var maxChildren = os.cpus().length;
console.log('max children: ' + maxChildren);
function getChild(callback) {
console.log('free: ' + freeChildren.length + ', busy: ' + busyChildren +
', req: ' + reqQueue.length);
if (freeChildren.length === 0) {
if (freeChildren.length + busyChildren >= maxChildren) {
reqQueue.push(callback);
} else {
// spawn new child
console.log('spawn new child');
var ch = fork(__filename, [ 'fib' ]);
busyChildren++;
callback(null, ch);
}
} else {
// hand out one child
var ch = freeChildren.pop();
busyChildren++;
callback(null, ch)
}
}
function returnChild(child) {
busyChildren--;
freeChildren.push(child);
console.log('free: ' + freeChildren.length + ', busy: ' + busyChildren +
', req: ' + reqQueue.length);
if (reqQueue.length > 0) {
getChild(function(err, ch) {
if (err) return;
var rcb = reqQueue.pop();
process.nextTick(function() { rcb(null, ch); });
});
}
}
var server = http.createServer(function(req, res) {
getChild(function(err, child) {
if (err) {
res.writeHead(500);
res.end('Could not get child.\n');
return;
}
child.once('message', function(m) {
res.writeHead(200);
res.end(m.result + "\n");
returnChild(child);
});
child.send({ input: 40 });
});
});
server.listen(8000);
console.log("server online at http://localhost:8000/")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment