From d041bda3ef6897bff7d1dc34e30686b502a48374 Mon Sep 17 00:00:00 2001 From: hhvn Date: Mon, 29 Jan 2024 17:53:49 +0000 Subject: Prevent concurrent read/write to status map --- status/00-status.go | 21 ++++++++++++++++----- 1 file changed, 16 insertions(+), 5 deletions(-) diff --git a/status/00-status.go b/status/00-status.go index bfd7bb9..109c49c 100644 --- a/status/00-status.go +++ b/status/00-status.go @@ -3,6 +3,7 @@ package status // import "hhvn.uk/hbspbar/status" import ( "fmt" "time" + "sync" "image" "image/color" @@ -15,14 +16,21 @@ var NewBlocks = make(chan *Blocks) var updates = make(chan *status) var statusid = make(map[string]int) -type Blocks map[int]*status +type Blocks struct { + l *sync.RWMutex + m map[int]*status +} func (b *Blocks) Len() int { - return len(map[int]*status(*b)) + b.l.RLock() + defer b.l.RUnlock() + return len(b.m) } func (b *Blocks) Get(i int) (s *status, ok bool) { - s, ok = (map[int]*status(*b))[i] + b.l.RLock() + defer b.l.RUnlock() + s, ok = b.m[i] return } @@ -33,16 +41,19 @@ type status struct { } func init() { + var mutex sync.RWMutex status := make(map[int]*status) + b := &Blocks{&mutex, status} go func() { for s := range updates { id := statusid[s.Name] + mutex.Lock() status[id] = s + mutex.Unlock() - b := Blocks(status) - NewBlocks <- &b + NewBlocks <- b } }() } -- cgit v1.2.3