node.js - 为什么 Node 会产生多个线程?

标签 node.js asynchronous io libuv

我列出了 Node 服务器的线程,以下是标准输出上的响应:

$ ps -e -T | grep 14209
14209 14209 ?        00:10:08 node
14209 14415 ?        00:00:00 V8 WorkerThread
14209 14416 ?        00:00:00 V8 WorkerThread
14209 14417 ?        00:00:00 V8 WorkerThread
14209 14418 ?        00:00:00 V8 WorkerThread
14209 14419 ?        00:00:00 node
14209 15894 ?        00:00:00 node
14209 15895 ?        00:00:00 node
14209 15896 ?        00:00:00 node
14209 15902 ?        00:00:00 node

我了解到nodejs是单线程的,同一个线程负责处理javascript代码。那么,最后五个线程的目的是什么?它们是由处理异步 I/O 的 libuv 生成的吗?

最佳答案

So, what is the purpose of last five threads? Are they spawned by libuv which handles asynchronous I/O?

至少其中一些(如果不是全部)是由于 libuv 造成的,是的。
该库有一个线程池(在 documentation 中明确提到)主要用于 fs 请求,尽管不仅仅用于它们:

libuv provides a threadpool which can be used to run user code and get notified in the loop thread. This thread pool is internally used to run all file system operations, as well as getaddrinfo and getnameinfo requests.

这是因为像 fs 请求这样的事情本质上是同步的,让它们看起来异步的唯一方法是在单独的线程上生成请求,然后在主线程上处理响应。

话虽这么说,JavaScript 环境确实是单线程的,但它并不强制底层库(主要是 v8libuv)不在内部使用线程来实现其目的。只要 JavaScript 运行时对用户来说是单线程的,就没有理由不使用线程。
实际上,这正是这些库在某种程度上执行其任务并提高性能的做法:它们生成线程并在内部使用它们。

关于node.js - 为什么 Node 会产生多个线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47159912/

相关文章:

node.js - 根据 Sequelize 中包含的数据进行查询

javascript - MongoDB选择_id数组的位置?

mysql - 使用 Nodemailer 获取 SQL 数据并发送多封电子邮件?

javascript - 套接字未定义,如果未定义则发送不发送

javascript - Promise.map 中的异步方法

c++ - 如何在 C++ 中处理异步套接字接收?

java - 如何将字符串变量插入文件路径?

c++ - ActiveMQ C++ 同步客户端

c - 输入文本文件未完全读取

java - 来自相对路径的 InputStream