Asynchronous programming in node.js speeds up CPU related tasks?

Earlier today I answered a question with this answer. In the example that I posted, I used the synchronous version of the call in the bcrypt node module, I decided to use the synchronous version of the call primarily because I thought that made the answer look a little cleaner, but I also did not think that it would affect performance because bcrypt is processor and memory, not I / O related. As I understand it, node used almost all of your code in a single thread, such as browsers, and used only background threads for operations such as I / O and database access. This led me to believe that tasks intensively related to the processor would still “block” the server, as there were no other threads to offload the work.

A comment on my review showed that my assumption was wrong, and after some research, I realized that I really did not understand how node.js handled such things. Asynchronous programming in node.js speeds up processor and memory calls? If so, how is this done?

+6
source share
1 answer

It depends on how the module is implemented.

If the module is implemented without streaming support, then yes, processor binding processing cannot be performed asynchronously. Some functions provide callbacks and my view is asynchronous, but they really aren't. They actually work synchronously and block the event loop. Examples of this in javascript are Array.forEach() .

But modules can be implemented for processing in the background thread. In this case, it is really asynchronous and can speed up the tasks associated with the CPU. At the very least, it frees up an event loop to handle incoming requests, while the background thread is busy computing.

An example of this is the crypto.pbkdf2() function in node's native Crypto module.

But how can modules execute code in other threads when node.js is running on the same thread?

The initial way this was implemented was that the module was not written in javascript, but was written in C / C ++ and linked to node.js via API add-ons.

But these days, even pure javascript modules and functions can create threads and / or processes. node has an experimental module called Cluster that installs a cluster of master / slave processes node. Your module or code can then run the processor-related task in the workflow, freeing up the main node process to handle the event loop. There are several thread cutting modules at npm. Just search for "thread" at npmjs.org.

So, yes, CPU-bound tasks can run faster, or at least not block the main event loop, starting asynchronously.

+7
source

Source: https://habr.com/ru/post/947705/


All Articles