3
0

Address data race in pkg/healtcheck

This commit is contained in:
Denis Arh
2022-04-04 16:50:29 +02:00
parent a797c847b1
commit 662f5155b9
2 changed files with 23 additions and 1 deletions
+9 -1
View File
@@ -6,6 +6,7 @@ import (
"fmt"
"io"
"strings"
"sync"
)
type (
@@ -28,6 +29,7 @@ type (
results []*result
checks struct {
l sync.RWMutex
cc []*check
}
)
@@ -50,10 +52,16 @@ func New() *checks {
// Add appends new check
func (c *checks) Add(fn checkFn, label string, description ...string) {
c.l.Lock()
defer c.l.Unlock()
c.cc = append(c.cc, &check{fn, &Meta{Label: label, Description: strings.Join(description, "")}})
}
func (c checks) Run(ctx context.Context) results {
func (c *checks) Run(ctx context.Context) results {
c.l.RLock()
defer c.l.RUnlock()
var rr = make([]*result, len(c.cc))
for i, c := range c.cc {
+14
View File
@@ -66,3 +66,17 @@ func Test_Healthy(t *testing.T) {
})
}
}
// tested with
// go test -count 10 -race -run Test_DataRace ./pkg/healthcheck/...
func Test_DataRace(t *testing.T) {
hc := New()
go func() {
hc.Add(func(ctx context.Context) error { return nil }, "hc1")
hc.Add(func(ctx context.Context) error { return nil }, "hc2")
hc.Add(func(ctx context.Context) error { return nil }, "hc3")
}()
go hc.Run(context.Background())
}