fix(player): race condition

This commit is contained in:
2022-02-19 18:18:40 +08:00
parent 953fcdba9e
commit 457dbfcac5
+11
View File
@@ -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