From 9c3c69125e54fc23d6ee89dc33465f9d1c9c1912 Mon Sep 17 00:00:00 2001 From: Thomas Karpiniec Date: Sun, 20 Oct 2024 13:50:09 +1100 Subject: [PATCH] Fix races in status message accumulation --- server/status.go | 18 +++++++++++++++--- 1 file changed, 15 insertions(+), 3 deletions(-) diff --git a/server/status.go b/server/status.go index accbcc9..260a0ce 100644 --- a/server/status.go +++ b/server/status.go @@ -2,11 +2,13 @@ package main import ( "code.octet-stream.net/broadcaster/protocol" + "sync" ) type ServerStatus struct { - statuses map[int]protocol.StatusMessage - changeWait chan bool + statuses map[int]protocol.StatusMessage + statusesMutex sync.Mutex + changeWait chan bool } var status ServerStatus @@ -19,11 +21,15 @@ func InitServerStatus() { } func (s *ServerStatus) MergeStatus(radioId int, status protocol.StatusMessage) { + s.statusesMutex.Lock() + defer s.statusesMutex.Unlock() s.statuses[radioId] = status s.TriggerChange() } func (s *ServerStatus) RadioDisconnected(radioId int) { + s.statusesMutex.Lock() + defer s.statusesMutex.Unlock() delete(s.statuses, radioId) s.TriggerChange() } @@ -34,7 +40,13 @@ func (s *ServerStatus) TriggerChange() { } func (s *ServerStatus) Statuses() map[int]protocol.StatusMessage { - return s.statuses + s.statusesMutex.Lock() + defer s.statusesMutex.Unlock() + c := make(map[int]protocol.StatusMessage) + for k, v := range s.statuses { + c[k] = v + } + return c } func (s *ServerStatus) ChangeChannel() chan bool { -- 2.39.5