-
-
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.
This file contains hidden or 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 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