UV_THREADPOOL_SIZE=size


将 libuv 线程池中使用的线程数设置为 size 个线程。

🌐 Set the number of threads used in libuv's threadpool to size threads.

Node.js 尽可能使用异步系统 API,但在这些 API 不存在的情况下,会使用 libuv 的线程池基于同步系统 API 创建异步 Node API。使用线程池的 Node.js API 有:

🌐 Asynchronous system APIs are used by Node.js whenever possible, but where they do not exist, libuv's threadpool is used to create asynchronous node APIs based on synchronous system APIs. Node.js APIs that use the threadpool are:

  • 除文件监视器 API 和那些显式同步的 API 外,所有 fs API
  • 异步加密 API,例如 crypto.pbkdf2()crypto.scrypt()crypto.randomBytes()crypto.randomFill()crypto.generateKeyPair()
  • dns.lookup()
  • 所有 zlib API,除了那些明确为同步的 API

由于 libuv 的线程池大小是固定的,这意味着如果由于任何原因其中的任何 API 运行时间较长,其他(看似无关的)在 libuv 线程池中运行的 API 的性能也会受到影响。为了解决这个问题,一种潜在的解决方案是通过将 'UV_THREADPOOL_SIZE' 环境变量设置为大于 4(当前默认值)的值来增加 libuv 线程池的大小。然而,通过在进程内部使用 process.env.UV_THREADPOOL_SIZE=size 进行设置并不能保证有效,因为线程池在用户代码运行之前很久的运行时初始化阶段就已被创建。更多信息,请参见 libuv 线程池文档

🌐 Because libuv's threadpool has a fixed size, it means that if for whatever reason any of these APIs takes a long time, other (seemingly unrelated) APIs that run in libuv's threadpool will experience degraded performance. In order to mitigate this issue, one potential solution is to increase the size of libuv's threadpool by setting the 'UV_THREADPOOL_SIZE' environment variable to a value greater than 4 (its current default value). However, setting this from inside the process using process.env.UV_THREADPOOL_SIZE=size is not guaranteed to work as the threadpool would have been created as part of the runtime initialisation much before user code is run. For more information, see the libuv threadpool documentation.