Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

237
Visualizações
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)
over 4 years ago · Santiago Trujillo
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda