From d60eba90a8faea861dec9f762c5a8a023c95214a Mon Sep 17 00:00:00 2001 From: mitchell Date: Tue, 19 Dec 2023 16:28:21 -0500 Subject: [PATCH] Iterate over processes asynchronously. Iterating over processes synchronously on macOS is particularly quite slow. --- internal/osutils/osutils.go | 32 +++++++++++++++++++++----------- 1 file changed, 21 insertions(+), 11 deletions(-) diff --git a/internal/osutils/osutils.go b/internal/osutils/osutils.go index 5c3e65782a..6a9e10ef32 100644 --- a/internal/osutils/osutils.go +++ b/internal/osutils/osutils.go @@ -8,6 +8,7 @@ import ( "path/filepath" "runtime" "strings" + "sync" "github.com/shirou/gopsutil/v3/process" @@ -138,21 +139,30 @@ func GetProcessesInUse(dir string) map[string]int32 { return inUse } + var wg sync.WaitGroup + var mutex sync.Mutex if runtime.GOOS != "linux" { dir = strings.ToLower(dir) // Windows and macOS filesystems are case-insensitive } for _, p := range procs { - exe, err := p.Exe() - if err != nil { - continue // probably a permission error; ignore - } - exeToCompare := exe - if runtime.GOOS != "linux" { - exeToCompare = strings.ToLower(exeToCompare) // Windows and macOS filesystems are case-insensitive - } - if strings.Contains(exeToCompare, dir) { - inUse[exe] = p.Pid - } + wg.Add(1) + go func(p *process.Process) { + defer wg.Done() + exe, err := p.Exe() + if err != nil { + return // probably a permission error; ignore + } + exeToCompare := exe + if runtime.GOOS != "linux" { + exeToCompare = strings.ToLower(exeToCompare) // Windows and macOS filesystems are case-insensitive + } + if strings.Contains(exeToCompare, dir) { + mutex.Lock() + inUse[exe] = p.Pid + mutex.Unlock() + } + }(p) } + wg.Wait() return inUse }