From 0b9266ba83756764ea00c787cf2734e8e3a1ba70 Mon Sep 17 00:00:00 2001 From: Dan Ballard Date: Wed, 21 Nov 2018 13:42:58 -0800 Subject: [PATCH] make writes to shared global hashmap threadsafe --- pidusage.go | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/pidusage.go b/pidusage.go index 993a9a2..b29ba7f 100644 --- a/pidusage.go +++ b/pidusage.go @@ -9,6 +9,7 @@ import ( "runtime" "strconv" "strings" + "sync" ) // SysInfo will record cpu and memory data @@ -33,6 +34,7 @@ type fn func(int) (*SysInfo, error) var fnMap map[string]fn var platform string var history map[int]Stat +var historyLock sync.Mutex var eol string func wrapper(statType string) func(pid int) (*SysInfo, error) { @@ -139,7 +141,9 @@ func stat(pid int, statType string) (*SysInfo, error) { seconds = 1 } + historyLock.Lock() history[pid] = *stat + historyLock.Unlock() sysInfo.CPU = (total / seconds) * 100 sysInfo.Memory = stat.rss * pageSize }