From b0561e3e6e7b6e4de28e66a4e6a0bd5c035427dd Mon Sep 17 00:00:00 2001 From: konakona418 Date: Sat, 13 Sep 2025 23:40:22 +0800 Subject: [PATCH] fix: inconsistency in getting thread pool size Use libuv's own OS-independent implementation to get env var UV_THREADPOOL_SIZE. --- src/threadpool.c | 39 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 38 insertions(+), 1 deletion(-) diff --git a/src/threadpool.c b/src/threadpool.c index 98d81cc7b..f9bdc4923 100644 --- a/src/threadpool.c +++ b/src/threadpool.c @@ -192,13 +192,45 @@ void uv__threadpool_cleanup(void) { static void init_threads(void) { + const char env_name[] = "UV_THREADPOOL_SIZE"; + uv_thread_options_t config; unsigned int i; + + size_t bufsize; + /* a size of 5 should work quite fine, as there won't be many threads + * and the MAX_THREADPOOL_SIZE is 1024 + */ + char fastvarbuf[5]; + char* varbuf; const char* val; + uv_sem_t sem; nthreads = ARRAY_SIZE(default_threads); - val = getenv("UV_THREADPOOL_SIZE"); + + bufsize = ARRAY_SIZE(fastvarbuf); + varbuf = NULL; + + int err = uv_os_getenv(env_name, fastvarbuf, &bufsize); + if (err == 0) + val = fastvarbuf; + else if (err == UV_ENOBUFS) { + /* this should not happen, but just in case */ + varbuf = uv__malloc(bufsize); + val = varbuf; + err = uv_os_getenv(env_name, varbuf, &bufsize); + + if (err != 0) { + /* failed again */ + val = NULL; + uv__free(varbuf); + } + } else { + /* UV_ENOENT and other err */ + val = NULL; + } + if (val != NULL) nthreads = atoi(val); if (nthreads == 0) @@ -206,6 +238,11 @@ static void init_threads(void) { if (nthreads > MAX_THREADPOOL_SIZE) nthreads = MAX_THREADPOOL_SIZE; + if (varbuf != NULL) { + uv__free(varbuf); + varbuf = NULL; + } + threads = default_threads; if (nthreads > ARRAY_SIZE(default_threads)) { threads = uv__malloc(nthreads * sizeof(threads[0]));