From c2c769acd55474456e3ffba129157e828fb77658 Mon Sep 17 00:00:00 2001
From: ale <ale@incal.net>
Date: Sat, 27 Dec 2014 17:00:15 +0000
Subject: [PATCH] make the BandwidthMonitor exit along with everything else

---
 node/bwmonitor/bwmonitor.go | 20 ++++++++++----------
 node/node.go                |  3 +++
 2 files changed, 13 insertions(+), 10 deletions(-)

diff --git a/node/bwmonitor/bwmonitor.go b/node/bwmonitor/bwmonitor.go
index be401144..baeeaff9 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 21fbcb02..ac9a3125 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 {
-- 
GitLab