1

In node.js

app.use((req, res, next) => {
  
  setImmediate( () = {
    heavyTask();
  });

  function heavyTask(){
    for (let i = 0; i < 100000; i++) {
      for (let i = 0; i < 100000; i++) {
        for (let i = 0; i < 3; i++) {

        }
      }
    }
  }

});

I set up 2 users (userA, userB) in local dev. Whenever I use userA to trigger this function, other users like userB has to wait in line although these users are performing simpler task that takes a few ms. I'm definitely misunderstood something about setImmediate. I thought it's supposed to prevent blocking of event loop so other users don't have to wait in line when other users do expensive calculation.

The answer I'm looking for is by example using this code above.

nice_dev
  • 17,053
  • 2
  • 21
  • 35
Ian
  • 11
  • 2
  • Does this help: https://stackoverflow.com/questions/40028377/is-it-possible-to-achieve-multithreading-in-nodejs – Henry Jul 03 '20 at 04:37
  • 2
    Well, you can make it asynchronous. I would also like to ask what is that nested for loop doing? Maybe there is room for optimization. – nice_dev Jul 03 '20 at 04:44
  • `setImmediate` will allow other tasks to execute before this one but once this task is running, it's still blocking the thread. If you were to run something like this, then at best you can have every iteration's logic run in a `setImmediate`/`setTimeout`. In that case `heavyTask` would still need about the same processing time but if another task comes up, it will not be blocked: different task is put on the queue -> `heavyTask` will finish the current iteration and put the next iteration on the queue -> the different task is picked up and processed -> `heavyTask` is next on the queue again. – VLAZ Jul 03 '20 at 04:57
  • @vivek_23 It's a game event that calculate results based on player input and sends it back as json object. All calculations are done within the function. It's a mixed of for loop and math calculations. I would try doing promise in my next test if it will work. – Ian Jul 03 '20 at 05:01
  • @VLAZ Thanks, I will try experimenting with that. – Ian Jul 03 '20 at 05:02
  • you could maybe use worker threads? could this fit to your app? – bill.gates Jul 03 '20 at 05:13
  • @Ifaruki Yeah, that will be one of my last resort. It it's really bad, I will just dump the function in Lambda in AWS. – Ian Jul 03 '20 at 05:28
  • Maybe `fork` can help? Move for loops in app.js and then do something like this: `const cp = require('child_process'); const task = cp.fork(__dirname + "/app.js"); task.on('close', () => { //response here })` – IvanPenga Jul 03 '20 at 07:15
  • @IvanPenga I decided to just separate the function in lambda. After reading a few articles, I concluded its ideal to avoid heavy task in node.js in itself. – Ian Jul 04 '20 at 08:22

0 Answers0