Skip to content

Commit

Permalink
Fix race in Flush and AddStatGenerator (#8)
Browse files Browse the repository at this point in the history
  • Loading branch information
Christopher Burnett authored and junr03 committed Apr 17, 2017
1 parent a81eedf commit afaa0fd
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 3 deletions.
9 changes: 6 additions & 3 deletions stats.go
Original file line number Diff line number Diff line change
Expand Up @@ -299,13 +299,13 @@ type statStore struct {
}

func (s *statStore) Flush() {
s.Lock()
defer s.Unlock()

for _, g := range s.statGenerators {
g.GenerateStats()
}

s.Lock()
defer s.Unlock()

for name, cv := range s.counters {
value := cv.latch()

Expand All @@ -328,6 +328,9 @@ func (s *statStore) Start(ticker *time.Ticker) {
}

func (s *statStore) AddStatGenerator(statGenerator StatGenerator) {
s.Lock()
defer s.Unlock()

s.statGenerators = append(s.statGenerators, statGenerator)
}

Expand Down
31 changes: 31 additions & 0 deletions stats_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package stats

import (
"sync"
"testing"
)

// Ensure flushing and adding generators does not race
func TestStats(t *testing.T) {
sink := &testStatSink{}
store := NewStore(sink, false)

scope := store.Scope("runtime")
g := NewRuntimeStats(scope)
var wg sync.WaitGroup
wg.Add(2)

go func() {
store.AddStatGenerator(g)
store.Flush()
wg.Done()
}()

go func() {
store.AddStatGenerator(g)
store.Flush()
wg.Done()
}()

wg.Wait()
}

0 comments on commit afaa0fd

Please sign in to comment.