From 4d45a9a65200b3bca92f05b99af2e6dd1808a275 Mon Sep 17 00:00:00 2001 From: Zuohui Yang <274048862@qq.com> Date: Wed, 21 Aug 2024 14:29:03 +0800 Subject: [PATCH] win, util: optimize the performance of uv_os_getppid (#4512) uv_os_getppid uses CreateToolhelp32Snapshot to enumerate processes and find the parent process PID.However, CreateToolhelp32Snapshot has poor performance.Use uv_once to improve performance. --- src/win/util.c | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/win/util.c b/src/win/util.c index bba37f89..84f4240c 100644 --- a/src/win/util.c +++ b/src/win/util.c @@ -75,6 +75,10 @@ static CRITICAL_SECTION process_title_lock; /* Frequency of the high-resolution clock. */ static uint64_t hrtime_frequency_ = 0; +/* Cache parent pid to optimize performance */ +static uv_once_t parent_pid_init_guard = UV_ONCE_INIT; +static int parent_pid = -1; + /* * One-time initialization code for functionality defined in util.c. @@ -317,8 +321,7 @@ uv_pid_t uv_os_getpid(void) { } -uv_pid_t uv_os_getppid(void) { - int parent_pid = -1; +static void uv__init_ppid(void) { HANDLE handle; PROCESSENTRY32 pe; DWORD current_pid = GetCurrentProcessId(); @@ -336,6 +339,11 @@ uv_pid_t uv_os_getppid(void) { } CloseHandle(handle); +} + + +uv_pid_t uv_os_getppid(void) { + uv_once(&parent_pid_init_guard, uv__init_ppid); return parent_pid; }