• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
    • Questions
    • Teachers
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

165
Views
Running Node js CPU heavy code in separate thread with cluster?

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)
about 3 years ago · Santiago Trujillo
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error