I have a class with a function that turned out to be pretty CPU intensive and I am trying to determine the best way to separate this out to another thread. I used the below code to test this, but I am not sure if this is the best way to accomplish this. Ultimately I would like to have a class with a CPU heavy function and be able to just choose to run it on a separate thread.
My working code:
var cluster = require('cluster')
if (!cluster.isMaster) { // cpuHog is only called inside the child process
console.log(`Worker is listening on pid:${process.pid}`);
process.on('message', (input) => {
console.log(`Request receved for input ${input}`)
cpuHog(input).then(output => process.send(output))
})
return; // exit if child
}
function cpuHog(input){
return new Promise( (resolve)=> { setTimeout(()=> {resolve(input*input)},2000) })
}
function createSeparateThread(input){
return new Promise((resolve,reject) => {
var worker = cluster.fork()
worker.on('message', resolve);
worker.send(input)
})
}
var input = 5
createSeparateThread(input).then( output => console.log(`Received result is ${output}`))
// My normal async node js code...
So if the above code is OK, how do I translate this to a Class instance?
var myClass = new MyClass()
// this should start a new thread
myClass.createSeparateThread(5)