commit d041bda3ef6897bff7d1dc34e30686b502a48374
parent 4e7b725a88ed1ad19cc67cbbbb46f3702c3bee97
Author: hhvn <dev@hhvn.uk>
Date: Mon, 29 Jan 2024 17:53:49 +0000
Prevent concurrent read/write to status map
Diffstat:
1 file changed, 16 insertions(+), 5 deletions(-)
diff --git 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
}
}()
}