tidy up loop control and mutex

This commit is contained in:
AtakanColak 2020-11-09 10:50:09 +03:00
parent b2a3574216
commit 277c95057b
1 changed files with 4 additions and 12 deletions

View File

@ -35,28 +35,21 @@ func loadAvgGoroutine() {
) )
counter, err := common.ProcessorQueueLengthCounter() counter, err := common.ProcessorQueueLengthCounter()
loadErr = err
if err != nil || counter == nil { if err != nil || counter == nil {
loadAvgMutex.Unlock() log.Println("gopsutil: unexpected processor queue length counter error, please file an issue on github")
log.Println("unexpected processor queue length counter error, please file an issue on github")
return return
} }
tick := time.NewTicker(samplingFrequency).C tick := time.NewTicker(samplingFrequency).C
for { for {
currentLoad, loadErr = counter.GetValue() currentLoad, err = counter.GetValue()
if loadErr != nil { loadAvgMutex.Lock()
goto SKIP loadErr = err
}
loadAvg1M = loadAvg1M*loadAvgFactor1M + currentLoad*(1-loadAvgFactor1M) loadAvg1M = loadAvg1M*loadAvgFactor1M + currentLoad*(1-loadAvgFactor1M)
loadAvg5M = loadAvg5M*loadAvgFactor5M + currentLoad*(1-loadAvgFactor5M) loadAvg5M = loadAvg5M*loadAvgFactor5M + currentLoad*(1-loadAvgFactor5M)
loadAvg15M = loadAvg15M*loadAvgFactor15M + currentLoad*(1-loadAvgFactor15M) loadAvg15M = loadAvg15M*loadAvgFactor15M + currentLoad*(1-loadAvgFactor15M)
SKIP:
loadAvgMutex.Unlock() loadAvgMutex.Unlock()
<-tick <-tick
loadAvgMutex.Lock()
} }
} }
@ -67,7 +60,6 @@ func Avg() (*AvgStat, error) {
func AvgWithContext(ctx context.Context) (*AvgStat, error) { func AvgWithContext(ctx context.Context) (*AvgStat, error) {
loadAvgGoroutineOnce.Do(func() { loadAvgGoroutineOnce.Do(func() {
loadAvgMutex.Lock() // lock to be unlocked by loadAvgGoroutine
go loadAvgGoroutine() go loadAvgGoroutine()
}) })
loadAvgMutex.RLock() loadAvgMutex.RLock()