Skip to content

Instantly share code, notes, and snippets.

@jarrettmeyer
Created March 3, 2016 11:27
Show Gist options
  • Select an option

  • Save jarrettmeyer/3e1e34d1921577036c04 to your computer and use it in GitHub Desktop.

Select an option

Save jarrettmeyer/3e1e34d1921577036c04 to your computer and use it in GitHub Desktop.
multiple threads in a NodeJS application
'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