Skip to content

Instantly share code, notes, and snippets.

@pmuellr
Last active Oct 13, 2015
Embed
What would you like to do?
#!/usr/bin/env NSOLID_APPNAME=clustery NSOLID_HUB=4001 nsolid
//------------------------------------------------------------------------------
// clustery is a program that uses the Node.js cluster module to launch
// a number of worker processes, that eat your CPU soring arrays of random
// numbers. It's intended as a sample program for N|Solid.
//
// If you have N|Solid installed, you can monitor the clustery master and
// workers with the command:
//
// NSOLID_APPNAME=clustery NSOLID_HUB=4001 nsolid clustery
//
// Then head over to your N|Solid console, maybe at http://localhost:3000 ,
// to watch the magic unfold.
//------------------------------------------------------------------------------
"use strict"
// see: https://nodejs.org/api/cluster.html
const cluster = require("cluster")
// if the single master, run master(), otherwise run as a worker
cluster.isMaster ? master() : worker()
//------------------------------------------------------------------------------
function master() {
// set the process name for `ps`
process.title = "clustery master"
console.log(`starting master`)
// fork a worker for the # of CPUs you have
require("os").cpus().forEach( cpu => cluster.fork() )
}
//------------------------------------------------------------------------------
function worker() {
// set the process name for `ps`
process.title = `clustery worker ${cluster.worker.id}`
console.log(`starting worker ${cluster.worker.id}`)
// do something, interval based on your worker index (0..workers)
setInterval(doSomething, cluster.worker.id * 10)
}
//------------------------------------------------------------------------------
function doSomething() {
// create an array of random numbers, then sort them. woo!
const SIZE = 5000
const arr = []
for (let i=0; i<SIZE; i++) {
arr.push(Math.random())
}
arr.sort()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment