Node.js 到底会创建多少个线程?

29

阅读了这个很棒的答案关于Node.js线程的性质后,我开始尝试使用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版本。

1个回答

33

更新:自从Node v6.0.0起,您可以通过--v8-pool-size标志来定义V8使用的线程数:

--v8-pool-size=num
设置V8的线程池大小,用于分配后台作业。 如果设置为0,则V8将根据在线处理器的数量选择适当的线程池大小。 如果提供的值大于V8的最大值,则会选择最大值。

V8会使用额外的4个线程来执行各种任务,例如与GC相关的后台任务和优化编译器任务。


哇,这是一个非常直截了当的答案。非常感谢! - Nhân Nguyễn
这种架构在最新的Node(17)版本中还是相同的吗? - Qwerty

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接