0

I am running the same asynchronous function in a loop without awaiting the function in a system with 2 CPUs. When I logged to the process id from inside the function, all of them have the same process id,

How does Node handle such parallel executions? Are both the CPUs being using perfectly? Do I need to manually fork process for each function in the loop?


function next(){
 console.log('main started', process.$
 const arr=[];
  for(let i=0; i<10000000; i++)    
                arr.push(1);
  arr.sort(function(a, b){return a<b});
 console.log('main ended')
}

function main(){
 next();
 next()
 next();
 next();
 next();
 next();
 console.log('-----------------------------$
}

main()


HTOP Screenshot

3
  • 1
    This might help: blog.risingstack.com/node-hero-async-programming-in-node-js Commented Sep 6, 2019 at 16:29
  • Show us your actual code in the loop and what the asynchronous operation is and we can answer a lot more specifically. node.js runs your Javascript as single threaded, but uses threads for some asynchronous operations (file I/O) and uses native asynchronous support for other types of operations (networking) and uses processes for things like spawn() and exec(). Show us the code for what you're actually doing so we can explain. Commented Sep 6, 2019 at 16:51
  • Please don't just post and disappear. That's not how stackoverflow works. When people engage with you to help, you will get better help if you are there to interact in a reasonable amount of time. Commented Sep 6, 2019 at 19:10

2 Answers 2

2

Node.js runs your actual Javascript in a single thread so it does not apply more than one CPU to your actual Javascript unless you specially design your code to put the CPU intensive tasks in Worker threads or you create your own separate processes with clustering or by using the child_process module to fire up your own additional processes and then farm work out to them. Just running your node.js program, a CPU intensive operation (like your long loop of sorting) will hog the CPU and block the event loop from processing other requests. It will not involve other CPUs in doing that sorting operation and will not use other CPUs for your Javascript.

When you run an asynchronous operation, there will be native code behind that operation and that native code may or may not use additional threads or processes. For example, file I/O uses a thread pool. Networking uses native OS asynchronous support (no threads). spawn() or exec() in child_process start new processes.

If you show us the actual code for your specific situation, we can answer more specifically about how that particular operation works.

How does Node handle such parallel executions?

It depends upon what the operation is.

Are both the CPUs being using perfectly?

Probably not, but we'd need to see your specific code.

Do I need to manually fork process for each function in the loop?

It depends upon the specific situation. For applying multiple CPUs to your actual Javascript (not asynchronous operations), then you would need multiple processes running your Javascript or perhaps the newest Worker thread api. If the parallelism is all in asynchronous operations, then the event driven nature of node.js is particularly good at managing many asynchronous operations at once and you may not even benefit from getting multiple CPUs involved because most of the time all node.js is doing is waiting for I/O to complete and many, many requests can already be in flight at the same time very efficiently in node.js.

For actually getting multiple CPUs applied to running your Javascript itself, then node.js has the clustering module which is pretty purpose-built for that. You can fire up a cluster process for each actual CPU core in your computer. Or, you can also use the new Worker thread api.

Also see these answers that discuss how to address CPU intensive code in node.js:

How to process huge array of objects in nodejs

How to apply clustering/spawing child process techniques for Node.js application having bouth IO bound and CPU bound tasks?

node.js socket.io server long latency

Is it possible somehow do multithreading in NodeJS?

How cpu intensive is too much for node.js (worried about blocking event loop)

Sign up to request clarification or add additional context in comments.

16 Comments

Thank you for your response. I have updated the post with the code
@ZeeshanShamsuddeen - That's not real code and doesn't show any real asynchronous operation. As I've said multiple times, strategies for parallelism depend upon the specific asynchronous operation. You will always get better answers here if you show your ACTUAL code, not pseudo code, not theoretical code, not theoretical questions with no code.
Apologies because I am new to StackOverFlow. I have edited the post with the actual code. Please have a look into this.
@ZeeshanShamsuddeen - Neither of those operations are CPU intensive or block the single thread of Javascript execution. The axios call is just a network request which uses no CPU at all while waiting for the response. The database call is also just a networking operation to another process (the database). There's no need to engage any other processes for that loop. Your performance will be limited by the ability of the target servers to respond, not by your node.js process.
@ jfriend00: Thank you. If the loop count is 100. This I am hitting an API 100 times and waiting for its response. Now, when all the responses comes back in parallel, will Node handle this perfectly? Will Node use both the CPUs during this time if needed? How to understand how many such parallel processes can be handled by Node?
|
1

You can use Promise.all that returns the resolved data from this asynchronous function. This way node doesn't wait for each array item to processed.

let results = await Promise.all(
array.map(arrayItem => executeAsynchronousFunctionWith(arrayItem))
);

The variable results is an array of resolved result.

1 Comment

this may not work as expected when using Promise.all with synchronous code

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.