Skip to content

Commit 9fd2df7

Browse files
committed
src: handling v8 thread pool of zero
fix: nodejs#42523 Problem: If no platform worker exists, Node.js doesn't shut down when background tasks exist. It keeps waiting in `NodePlatform::DrainTasks`. Observation: It seems that Node.js used to use V8's `DefaultPlatform` implementation, which chooses a suitable default value in case that `--v8-pool-size=0` is given as a command-line option. However, Node.js currently uses its own v8::Platform implementation, `NodePlatform`. It doesn't have the logic to handle the case. I referred to nodejs#4344 to track the issue.
1 parent 33cbdb3 commit 9fd2df7

File tree

3 files changed

+31
-3
lines changed

3 files changed

+31
-3
lines changed

doc/api/cli.md

+1-3
Original file line numberDiff line numberDiff line change
@@ -1368,11 +1368,9 @@ added: v5.10.0
13681368

13691369
Set V8's thread pool size which will be used to allocate background jobs.
13701370

1371-
If set to `0` then V8 will choose an appropriate size of the thread pool based
1371+
If set to `0` then Node.js will choose an appropriate size of the thread pool based
13721372
on the number of online processors.
13731373

1374-
If the value provided is larger than V8's maximum, then the largest value
1375-
will be chosen.
13761374

13771375
### `--zero-fill-buffers`
13781376

src/node_platform.cc

+15
Original file line numberDiff line numberDiff line change
@@ -45,6 +45,19 @@ static void PlatformWorkerThread(void* data) {
4545
}
4646
}
4747

48+
static int GetActualThreadPoolSize(int thread_pool_size) {
49+
if (thread_pool_size < 1) {
50+
uv_cpu_info_t* cpu_info;
51+
int count;
52+
53+
if (uv_cpu_info(&cpu_info, &count) == 0) {
54+
uv_free_cpu_info(cpu_info, count);
55+
thread_pool_size = count - 1;
56+
}
57+
}
58+
return std::max(thread_pool_size, 1);
59+
}
60+
4861
} // namespace
4962

5063
class WorkerThreadsTaskRunner::DelayedTaskScheduler {
@@ -340,6 +353,8 @@ NodePlatform::NodePlatform(int thread_pool_size,
340353
// current v8::Platform instance.
341354
SetTracingController(tracing_controller_);
342355
DCHECK_EQ(GetTracingController(), tracing_controller_);
356+
357+
thread_pool_size = GetActualThreadPoolSize(thread_pool_size);
343358
worker_thread_task_runner_ =
344359
std::make_shared<WorkerThreadsTaskRunner>(thread_pool_size);
345360
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
// Flags: --v8-pool-size=0
2+
'use strict';
3+
4+
const common = require('../common');
5+
const assert = require('assert');
6+
const { Worker, isMainThread } = require('worker_threads');
7+
8+
if (isMainThread) {
9+
const w = new Worker(__filename);
10+
w.on('online', common.mustCall());
11+
w.on('exit', common.mustCall((code) => assert.strictEqual(code, 0)));
12+
process.on('exit', (code) => {
13+
assert.strictEqual(code, 0);
14+
});
15+
}

0 commit comments

Comments
 (0)