Created
March 3, 2016 11:27
-
-
Save jarrettmeyer/3e1e34d1921577036c04 to your computer and use it in GitHub Desktop.
multiple threads in a NodeJS application
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
| 'use strict'; | |
| const args = process.argv; | |
| const cluster = require('cluster'); | |
| function getThreads() { | |
| let threads = 1; | |
| let tag = args.indexOf('--threads'); | |
| if (tag > 0) { | |
| let newThreads = parseInt(args[tag + 1], 10); | |
| if (newThreads > threads) { | |
| threads = newThreads; | |
| } | |
| } | |
| return threads; | |
| } | |
| function start(worker) { | |
| console.info(`Starting application. Worker ${worker.id}.`); | |
| setTimeout(() => { | |
| worker.disconnect(); | |
| }, 1000); | |
| } | |
| if (cluster.isMaster) { | |
| let threads = getThreads(); | |
| console.info(`Number of threads: ${threads}`); | |
| for (let i = 0; i < threads; i++) { | |
| cluster.fork(); | |
| } | |
| } | |
| else { | |
| start(cluster.worker); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment