diff --git a/player/main.go b/player/main.go index d5cbfeb..25cd6b1 100644 --- a/player/main.go +++ b/player/main.go @@ -6,6 +6,7 @@ import ( "fmt" "net/http" "os" + "sync" "time" ) @@ -41,6 +42,7 @@ func main() { var viewers = make(map[string]Viewer) var mirrorActivity = make(map[int]int) + var lock sync.Mutex // Handle view counting http.HandleFunc("/viewcount", func(w http.ResponseWriter, r *http.Request) { @@ -58,6 +60,7 @@ func main() { } // Update the last active time + lock.Lock() viewers[ip] = Viewer{ LastActive: now, ActiveMirror: metric.ActiveMirror, @@ -68,6 +71,8 @@ func main() { TotalCount: len(viewers), ByMirror: mirrorActivity, } + lock.Unlock() + if err := json.NewEncoder(w).Encode(response); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return @@ -83,11 +88,13 @@ func main() { var now = time.Now().Unix() // Remove any viewers that have not been active in the last 10 seconds + lock.Lock() for ip, viewer := range viewers { if now-viewer.LastActive > 10 { delete(viewers, ip) } } + lock.Unlock() } }() @@ -105,7 +112,9 @@ func main() { var last_count = 0 for { var now = time.Now().Format(time.RFC3339) + lock.Lock() var count = len(viewers) + lock.Unlock() // If the viewer count has changed, log it if count != last_count { @@ -133,10 +142,12 @@ func main() { var counts = make(map[int]int) // Loop through all viewers + lock.Lock() for _, viewer := range viewers { // Increment the mirror count counts[viewer.ActiveMirror]++ } + lock.Unlock() // Check if the counts have changed var changed = false