Created
August 6, 2019 11:18
-
-
Save vinzdef/5d058dc30bf0532c5c9d9d2f6a0fb494 to your computer and use it in GitHub Desktop.
Fork Process in Cluster
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
const server = require('./server.js') | |
const numCPUs = require('os').cpus().length | |
const cluster = require('cluster') | |
function makeCluster() { | |
return new Promise((resolve, reject) => { | |
if (cluster.isMaster) { | |
for (let i = 0; i < numCPUs; i++) { | |
cluster.fork() | |
} | |
cluster.on('exit', (worker, code, signal) => { | |
console.log(`Worker ${worker.process.pid} died`) | |
}) | |
resolve() | |
} else { | |
console.log(`Fork ${cluster.worker.id} is spawning`) | |
server.spawn() | |
.then(resolve) | |
.catch(reject) | |
} | |
}) | |
} | |
makeCluster() | |
.then(_ => { | |
console.log('Child spawned') | |
}) | |
.catch(e => { | |
console.log(`Fork failed: ${e}`) | |
}) |
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
module.exports = { | |
spawn: function() { | |
return new Promise(res => { | |
console.log('[!!!!] Spawned process') | |
res() | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment