Permalink
Browse files

Use the new cluster module to utilize multiple CPUs.

  • Loading branch information...
1 parent 103ae50 commit 82445f942be704c247194220c2fba5963300d7f0 @cskr committed Dec 9, 2011
Showing with 29 additions and 7 deletions.
  1. +29 −7 grasshopper/lib/routes.js
View
@@ -18,6 +18,8 @@ exports.api = {};
var http = require('http'),
https = require('https'),
+ os = require('os'),
+ cluster = require('cluster'),
context = require('./context'),
dispatcher = require('./dispatcher'),
RouteMatcher = dispatcher.RouteMatcher;
@@ -71,6 +73,22 @@ exports.api.serveSecure = function(port, credentials, hostname, callback) {
return startServer(secureRoutes, port, credentials, hostname, callback);
};
+exports.api.cluster = function(server, port, hostname, forks) {
+ if(typeof hostname == 'number') {
+ forks = hostname;
+ hostname = undefined;
+ }
+
+ if(forks === undefined) forks = os.cpus().length;
+ if(cluster.isMaster) {
+ for(var i = 0; i < forks; i++) {
+ cluster.fork();
+ }
+ } else {
+ listen(server, port, hostname);
+ }
+};
+
exports.api.stop = function() {
servers.forEach(function(server) {
server.close();
@@ -120,14 +138,18 @@ function startServer(routes, port, credentials, hostname, callback) {
servers.push(server);
if(typeof port == 'number') {
- server.listen(port, hostname, function() {
- var url = (credentials ? 'https://' : 'http://')
- + (hostname || 'localhost') + ':'
- + port;
- console.log('Hopping at ' + url + '. Use Ctrl+C to stop.');
- if(callback) callback();
- });
+ listen(server, port, hostname, callback);
}
return server;
}
+
+function listen(server, port, hostname, callback) {
+ server.listen(port, hostname, function() {
+ var url = (server.cert !== undefined ? 'https://' : 'http://')
+ + (hostname || 'localhost') + ':'
+ + port;
+ console.log('Hopping at ' + url + '. Use Ctrl+C to stop.');
+ if(callback) callback();
+ });
+}

0 comments on commit 82445f9

Please sign in to comment.