Last active
August 7, 2016 02:54
-
-
Save montanaflynn/ffaf7b1ca2ca24e4044d to your computer and use it in GitHub Desktop.
Parallel cpu node
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
// The magic module that makes this all possible | |
var cluster = require('cluster') | |
// Boss gets everyone to work | |
if (cluster.isMaster) { | |
// The crew made of worker threads | |
var crew = [] | |
// The state of the job to pass between boss and workers | |
var state = 0 | |
// For each CPU thread available | |
for (var i = 0; i < require('os').cpus().length; i++) { | |
// Add worker to the crew | |
crew.push(cluster.fork()) | |
// Send worker his first job | |
crew[i].send(state++) | |
// Set up walkie-talkie for messaging | |
crew[i].on('message', function(msg) { | |
// Print the message recieved from worker | |
console.log(msg) | |
// Send the worker his next job | |
this.send(state++) | |
}) | |
} | |
} | |
// The workers do the work and report back when done | |
if (cluster.isWorker) { | |
// Reference to worker | |
var workerID = cluster.worker.id | |
// Have worker reply to messages | |
process.on('message', function(msg) { | |
// Print the message recieved from boss | |
console.log("Boss tells worker #"+workerID+" go to plot #"+msg) | |
// Pretend like we're doing stuff for a random amout of time (500-1000ms) | |
setTimeout(function(){ | |
// Send the boss word that we did the work | |
process.send("Worker #" + workerID + " is done with plot #"+msg) | |
},Math.floor(Math.random() * 500) + 500) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment