Created
December 24, 2014 22:01
-
-
Save maxant/4e7f670a638d40b980d7 to your computer and use it in GitHub Desktop.
Scaling up using child processes
This file contains 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
// //////////////// | |
// Parent | |
// //////////////// | |
... | |
var cp = require('child_process'); | |
... | |
//TODO use config to decide how many child processes to start | |
var NUM_KIDS = 2; | |
var PRODUCT_IDS = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', | |
'10', '11', '12', '13', '14', '15', '16', '17', '18', '19', | |
... | |
]; | |
var chunk = PRODUCT_IDS.length / NUM_KIDS; | |
var kids = new Map(); | |
for (var i=0, j=PRODUCT_IDS.length; i<j; i+=chunk) { | |
var n = cp.fork('./lib/trading-engine-child.js'); | |
n.on('message', messageFromChild); | |
var temparray = PRODUCT_IDS.slice(i,i+chunk); | |
logger.info('created child process for products ' + temparray); | |
_.each(temparray, function(e){ | |
logger.debug('mapping productId "' + e + '" to child process ' + n.pid); | |
kids.set(e, n); | |
}); | |
} | |
... | |
// //////////////// | |
// Child | |
// //////////////// | |
process.on('message', function(model) { | |
logger.debug('received command: "' + model.command + '"'); | |
if(model.command == t.EventType.PURCHASE){ | |
var buyer = ... | |
var po = new m.PurchaseOrder(model.what.productId, model.what.quantity, model.what.maxPrice, model.id); | |
buyer.addPurchaseOrder(po); | |
}else if(model.command == t.EventType.SALE){ | |
... | |
}else{ | |
var msg = 'Unknown command ' + model.command; | |
process.send({id: model.id, err: msg}); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment