diff options
| author | hhvn <dev@hhvn.uk> | 2024-01-29 17:53:49 +0000 |
|---|---|---|
| committer | hhvn <dev@hhvn.uk> | 2024-01-29 17:53:49 +0000 |
| commit | d041bda3ef6897bff7d1dc34e30686b502a48374 (patch) | |
| tree | 668942150ca292df3a432eb5d6a0bcf95df16ec8 /status/00-status.go | |
| parent | 4e7b725a88ed1ad19cc67cbbbb46f3702c3bee97 (diff) | |
Prevent concurrent read/write to status map
Diffstat (limited to 'status/00-status.go')
| -rw-r--r-- | status/00-status.go | 21 |
1 files 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 } }() } |