Created
December 8, 2017 00:43
-
-
Save tlhunter/fd38772362bc2f11395f967bf509013a to your computer and use it in GitHub Desktop.
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
// parent.js | |
const fork = require('child_process').fork; | |
const CHILDREN = require('os').cpus().length; | |
const pool = []; | |
const OPTS = { | |
stdio: [0, 1, 2, 'ipc'] | |
}; | |
console.log(`Parent running with pid ${process.pid}`); | |
for (let child_id = 0; child_id < CHILDREN; child_id++) { | |
const child = fork('./child.js', [String(child_id)], OPTS); | |
pool.push(child); | |
child.on('message', message => { | |
// console.log('MESSAGE', child_id, message); | |
}); | |
} | |
// Send 1M messages | |
const getWorker = roundRobin(); | |
for (let i = 0; i < 1000000; i++) { | |
const child = getWorker(); | |
child.send({doWork: i}); | |
if (i % 1000 === 0) { | |
console.log(`${i}/1000000`); | |
} | |
} | |
function roundRobin() { | |
let pointer = -1; | |
return function() { | |
pointer++; | |
if (pointer >= pool.length) { | |
pointer = 0; | |
} | |
return pool[pointer]; | |
} | |
} | |
// child.js | |
if (!process.send) { | |
throw new Error("Must be run as a child process!"); | |
} | |
const child_id = process.argv[2]; | |
console.log(`Child ${child_id} running with pid ${process.pid}`); | |
// console.log('ENV', child_id, JSON.stringify(process.env)); | |
process.on('message', message => { | |
// console.log('CHILD MESSAGE', child_id, message); | |
const data = Math.sqrt(message.doWork); | |
process.send({ | |
work: 'done', | |
data, | |
worker: child_id, | |
input: message.doWork | |
}); | |
}); | |
/* | |
setTimeout(() => { | |
process.send(`Hello sent to parent from child ${child_id}`); | |
process.exit(); | |
}, Math.random() * 5000 + 5000); // Between 5s and 10s | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment