Do nodejs async functions use all CPU cores?

为君一笑 提交于 2019-12-25 02:35:19

问题


If I use async functions, or functions with callbacks like the native fs module, http etc, will they run by default across all cpu cores?

Or the entire thing will just use 1 core?


回答1:


Some asynchronous operations in node.js (such as file I/O in the fs module) will use additional threads within the node.js process via a thread pool in libuv. It would depend upon the size of your thread pool and what types of operations and upon your host OS for how many additional CPUs will be engaged. It does not necessarily help overall throughput to engage many CPUs on file I/O that is all going through the same disk since reading/writing is often bottlenecked by the position of the read/write head on the disk anyway.

Some asynchronous operations such as networking (like the http module) are non-blocking and asynchronous by nature and do not do their networking with threads or trigger any meaningful use of additional CPUs.

None of this will run your own Javascript in multiple threads since Javascript itself all executes in one thread.

To fully engage multiple CPUs, you can:

  1. Put some of your own Javascript into the new nodejs Worker Threads and communicate back to the main node.js thread via messaging.
  2. Fire up your own node.js child processes to do work in those child processes and communicate back results using one of the many interprocess communications options.
  3. Use node.js clustering so that incoming requests can be split among available queues. This requires making sure any server state is shareable among all the clustered processes (typically stored in some database that all processes can access). This will allow separate requests to use separate CPUs - it won't help a single request use more CPUs. You would need to use #1 and/or #2 for that.


来源:https://stackoverflow.com/questions/58384542/do-nodejs-async-functions-use-all-cpu-cores

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!