diff --git a/node/bwmonitor/bwmonitor.go b/node/bwmonitor/bwmonitor.go index be401144d34fd313e4ed236f3a191476095b6c81..baeeaff980522b685be131ba0db9632283e582cc 100644 --- a/node/bwmonitor/bwmonitor.go +++ b/node/bwmonitor/bwmonitor.go @@ -7,6 +7,7 @@ import ( "regexp" "strconv" "strings" + "sync" "time" ) @@ -43,8 +44,9 @@ type BandwidthMonitor struct { counter uint64 stamp time.Time period time.Duration - stop chan bool rate float64 + + lock sync.Mutex } func NewBandwidthMonitor(dev string) *BandwidthMonitor { @@ -52,32 +54,30 @@ func NewBandwidthMonitor(dev string) *BandwidthMonitor { device: dev, stamp: time.Now(), period: 30 * time.Second, - stop: make(chan bool), } - go bw.run() return bw } -func (bw *BandwidthMonitor) Close() { - close(bw.stop) -} - func (bw *BandwidthMonitor) GetRate() float64 { + bw.lock.Lock() + defer bw.lock.Unlock() return bw.rate } -func (bw *BandwidthMonitor) run() { +func (bw *BandwidthMonitor) Run(stop chan bool) { t := time.NewTicker(bw.period) for { select { case <-t.C: if c, err := getBytesSentForDevice(bw.device); err == nil { now := time.Now() - bw.rate = float64(c - bw.counter) / now.Sub(bw.stamp).Seconds() + bw.lock.Lock() + bw.rate = float64(c-bw.counter) / now.Sub(bw.stamp).Seconds() bw.counter = c bw.stamp = now + bw.lock.Unlock() } - case <-bw.stop: + case <-stop: return } } diff --git a/node/node.go b/node/node.go index 21fbcb02179ec86567f4831de5e7ad1e8335d4ad..ac9a31251fa921cf989855bb043c1547580aa56e 100644 --- a/node/node.go +++ b/node/node.go @@ -391,6 +391,9 @@ func (rc *RadioNode) Start() { // Icecast status checker. rc.icecast.Run, + + // Bandwidth monitor. + rc.bw.Run, } for _, fn := range bgfuncs {