nodejs异步函数是否使用所有CPU内核? [英] Do nodejs async functions use all CPU cores?

查看:112
本文介绍了nodejs异步函数是否使用所有CPU内核?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我使用异步函数,或者使用带有回调函数的函数(例如本机fs模块,http等),则默认情况下它们会在所有cpu内核上运行吗?

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?

还是整个东西将只使用1个内核?

Or the entire thing will just use 1 core?

推荐答案

node.js中有一些异步操作(例如<$中的文件I / O) c $ c> fs 模块)将通过libuv中的线程池在node.js进程中使用其他线程。这将取决于您的线程池的大小,操作的类型以及要使用多少个其他CPU的主机操作系统。在文件I / O上占用多个CPU的情况下,这并不一定有助于提高整体吞吐量,因为文件I / O上的所有CPU都始终受到磁盘上读写头位置的限制。

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.

某些异步操作(例如联网)(例如 http 模块)本质上是非阻塞且异步的,并且不使用

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.

由于Javascript本身全部在一个线程中执行,因此这些都不会在多个线程中运行您自己的Javascript。

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

要完全使用多个CPU,您可以:

To fully engage multiple CPUs, you can:


  1. 将自己的一些Javascript放入新的nodejs Worker线程,并通过消息传递回node.js主线程。

  2. 启动您自己的node.js子进程以在这些子进程中进行工作并进行通信使用许多进程间通信选项之一返回结果。

  3. 使用node.js集群,以便可以在可用队列之间分配传入请求。这要求确保任何服务器状态在所有集群进程之间都是可共享的(通常存储在所有进程可以访问的某个数据库中)。这将允许单独的请求使用单独的CPU-不会帮助单个请求使用更多的CPU。为此,您需要使用#1和/或#2。

  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.

这篇关于nodejs异步函数是否使用所有CPU内核?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆