Last active
October 13, 2015 05:03
-
-
Save pmuellr/a32db793ba5bbd711e65 to your computer and use it in GitHub Desktop.
This file contains 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
#!/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