diff --git a/player/main.go b/player/main.go index 25cd6b1..0eb5e5e 100644 --- a/player/main.go +++ b/player/main.go @@ -42,7 +42,8 @@ func main() { var viewers = make(map[string]Viewer) var mirrorActivity = make(map[int]int) - var lock sync.Mutex + var lockViewers sync.Mutex + var lockMirrorActivity sync.Mutex // Handle view counting http.HandleFunc("/viewcount", func(w http.ResponseWriter, r *http.Request) { @@ -60,18 +61,21 @@ func main() { } // Update the last active time - lock.Lock() + lockViewers.Lock() viewers[ip] = Viewer{ LastActive: now, ActiveMirror: metric.ActiveMirror, } + var viewersCount = len(viewers) + lockViewers.Unlock() // Respond + lockMirrorActivity.Lock() var response = ViewCountResponse{ - TotalCount: len(viewers), + TotalCount: viewersCount, ByMirror: mirrorActivity, } - lock.Unlock() + lockMirrorActivity.Unlock() if err := json.NewEncoder(w).Encode(response); err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) @@ -88,13 +92,13 @@ func main() { var now = time.Now().Unix() // Remove any viewers that have not been active in the last 10 seconds - lock.Lock() + lockViewers.Lock() for ip, viewer := range viewers { if now-viewer.LastActive > 10 { delete(viewers, ip) } } - lock.Unlock() + lockViewers.Unlock() } }() @@ -112,9 +116,9 @@ func main() { var last_count = 0 for { var now = time.Now().Format(time.RFC3339) - lock.Lock() + lockViewers.Lock() var count = len(viewers) - lock.Unlock() + lockViewers.Unlock() // If the viewer count has changed, log it if count != last_count { @@ -142,21 +146,23 @@ func main() { var counts = make(map[int]int) // Loop through all viewers - lock.Lock() + lockViewers.Lock() for _, viewer := range viewers { // Increment the mirror count counts[viewer.ActiveMirror]++ } - lock.Unlock() + lockViewers.Unlock() // Check if the counts have changed var changed = false + lockMirrorActivity.Lock() for mirror, count := range counts { if count != mirrorActivity[mirror] { changed = true break } } + lockMirrorActivity.Unlock() // If the counts have changed, log them if changed { @@ -166,7 +172,9 @@ func main() { } // Update the mirror activity + lockMirrorActivity.Lock() mirrorActivity = counts + lockMirrorActivity.Unlock() time.Sleep(time.Second) } }()