简体   繁体   English

为什么 Node.js 每个进程旋转 7 个线程

[英]Why Node.js spins 7 threads per process

When a Node.js process is spun up top command shows 7 threads attached to the process.当 Node.js 进程启动时,top 命令显示附加到该进程的 7 个线程。 What are all these threads doing?所有这些线程在做什么? Also, as the load on the API increases, with the request handlers themselves asynchronously awaiting other upstream API calls does Node spawn additional worker threads?此外,随着 API 上的负载增加,请求处理程序本身异步等待其他上游 API 调用是否会产生额外的工作线程? I see in top that it does that.我在上面看到它是这样做的。 But I was thinking this only happens for file I/o.但我认为这只发生在文件 I/o 上。 Why does it need these additional worker threads?为什么它需要这些额外的工作线程?

LIBUV (the underlying cross platform system library that node.js is built-on) uses a thread pool for certain operations such as disk I/O and some crypto operations. LIBUV(node.js 构建的底层跨平台系统库)使用线程池进行某些操作,例如磁盘 I/O 和一些加密操作。 By default that thread pool contains 4 threads.默认情况下,线程池包含 4 个线程。

Plus, there is a thread for the execution of your Javascript so that accounts for 5.另外,还有一个线程用于执行您的 Javascript,因此占 5。

Then, it appears there is a thread used by the garbage collector for background marking of objects (per this reference from a V8 developer ) and this article .然后,垃圾收集器似乎使用了一个线程来对对象进行背景标记(根据V8 开发人员的这个参考)和这篇文章 That would make 6.那将是6。

I don't know for sure what the 7th one would be.我不知道第七个会是什么。 It's possible there's a thread used by the event loop itself.事件循环本身可能使用了一个线程。

Then, starting some time around 2018, it appears that nodejs switched to a separate set of threads for DNS requests (separate from the file I/O thread pool).然后,从 2018 年左右开始,nodejs 似乎切换到一组单独的线程用于 DNS 请求(与文件 I/O 线程池分开)。 This was probably because of problems in node.js where 4 slow DNS requests could block all file I/O because they took over the thread pool.这可能是因为 node.js 中的问题,其中 4 个慢速 DNS 请求可能会阻塞所有文件 I/O,因为它们接管了线程池。 So, now it looks like node.js used the C-ARES library for DNS which makes its own set of threads.所以,现在看起来 node.js 使用了 DNS 的C-ARES 库,它创建了自己的线程集。

FYI, you can actually control the thread pool size with the UV_THREADPOOL_SIZE environment variable.仅供参考,您实际上可以使用UV_THREADPOOL_SIZE环境变量控制线程池大小。


And, of course, you can create your own Worker Threads that actually create new instances of the V8 Javascript execution engine (so they will likely end up creating more than one new thread).而且,当然,您可以创建自己的工作线程来实际创建 V8 Javascript 执行引擎的新实例(因此它们最终可能会创建多个新线程)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM