Skip to content

Commit

Permalink
Merge pull request #1380 from shirou/feature/readable_error_on_load_w…
Browse files Browse the repository at this point in the history
…indows

[load][windows]: add error detail and context handling.
  • Loading branch information
shirou committed Nov 30, 2022
2 parents 34cc43d + 231d6f3 commit 30aa851
Showing 1 changed file with 16 additions and 6 deletions.
22 changes: 16 additions & 6 deletions load/load_windows.go
Expand Up @@ -26,7 +26,7 @@ var (
// TODO instead of this goroutine, we can register a Win32 counter just as psutil does
// see https://psutil.readthedocs.io/en/latest/#psutil.getloadavg
// code https://github.com/giampaolo/psutil/blob/8415355c8badc9c94418b19bdf26e622f06f0cce/psutil/arch/windows/wmi.c
func loadAvgGoroutine() {
func loadAvgGoroutine(ctx context.Context) {
var (
samplingFrequency time.Duration = 5 * time.Second
loadAvgFactor1M float64 = 1 / math.Exp(samplingFrequency.Seconds()/time.Minute.Seconds())
Expand All @@ -37,20 +37,30 @@ func loadAvgGoroutine() {

counter, err := common.ProcessorQueueLengthCounter()
if err != nil || counter == nil {
log.Println("gopsutil: unexpected processor queue length counter error, please file an issue on github: err")
log.Printf("unexpected processor queue length counter error, %v\n", err)
return
}

tick := time.NewTicker(samplingFrequency).C
for {

f := func() {
currentLoad, err = counter.GetValue()
loadAvgMutex.Lock()
loadErr = err
loadAvgMutex.Lock()
loadAvg1M = loadAvg1M*loadAvgFactor1M + currentLoad*(1-loadAvgFactor1M)
loadAvg5M = loadAvg5M*loadAvgFactor5M + currentLoad*(1-loadAvgFactor5M)
loadAvg15M = loadAvg15M*loadAvgFactor15M + currentLoad*(1-loadAvgFactor15M)
loadAvgMutex.Unlock()
<-tick
}

f() // run first time
for {
select {
case <-ctx.Done():
return
case <-tick:
f()
}
}
}

Expand All @@ -61,7 +71,7 @@ func Avg() (*AvgStat, error) {

func AvgWithContext(ctx context.Context) (*AvgStat, error) {
loadAvgGoroutineOnce.Do(func() {
go loadAvgGoroutine()
go loadAvgGoroutine(ctx)
})
loadAvgMutex.RLock()
defer loadAvgMutex.RUnlock()
Expand Down

0 comments on commit 30aa851

Please sign in to comment.