Node 实际创建了多少个线程?

How many threads does Node actually create?

阅读 this great answer 关于 Node 的线程性质后, 我开始玩 UV_THREADPOOL_SIZE 系统变量来改变线程池的大小,我发现了一些有趣的东西:

当我设置

process.env.UV_THREADPOOL_SIZE = 10;

我的 Node 进程有 15 个线程(我认为应该是 10 + 1 个主 Node 线程 = 11)。

看看我的脚本:

process.env.UV_THREADPOOL_SIZE = 10;

//init thread pool by calling `readFile` function
require('fs').readFile(__filename, 'utf8', function(err, content) {});

//make node not exiting
setInterval(function() {}, 1000);

在运行之后我输入:

ps -Lef | grep test.js | grep -v grep

得到如下结果:

olegssh   4869  4301  4869  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4870  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4871  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4872  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4873  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4874  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4875  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4876  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4877  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4878  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4879  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4880  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4881  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4882  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js
olegssh   4869  4301  4883  0   15 16:38 pts/0    00:00:00 /home/olegssh/node/bin/node test.js

如您所见,有 15 个线程 运行。

如果我设置 UV_THREADPOOL_SIZE = 1,我得到 6 个线程。

如果我注释掉 readFile 行(因此线程池未初始化),我得到 5 个线程。

所以我得出结论,Node在启动时创建了5个线程。为什么不是 1?

有人可以解释一下吗?

编辑: 我正在使用全新的 Node 4.0.0

更新: 从节点 v6.0.0 开始,您可以通过 --v8-pool-size 标志定义 V8 使用的线程数:

--v8-pool-size=num
Set V8's thread pool size which will be used to allocate background jobs. If set to 0 then V8 will choose an appropriate size of the thread pool based on the number of online processors. If the value provided is larger than V8's maximum, then the largest value will be chosen.

4 个额外线程是 for use by V8。 V8 使用这些线程执行各种任务,例如 GC 相关的后台任务和优化编译器任务。