Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 4 additions & 5 deletions metriks/gauge.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ package metriks

import (
"context"
"sync"
"sync/atomic"
"time"

Expand All @@ -24,7 +23,7 @@ type PersistentGauge struct {
ticker *time.Ticker
cancel context.CancelFunc
dur time.Duration
wg sync.WaitGroup
donec chan struct{}
}

// Set will replace the value with a new one, it returns the old value
Expand All @@ -48,11 +47,10 @@ func (g *PersistentGauge) report(v int32) {
}

func (g *PersistentGauge) start(ctx context.Context) {
g.wg.Add(1)
for {
select {
case <-ctx.Done():
g.wg.Done()
close(g.donec)
return
case <-g.ticker.C:
g.report(atomic.LoadInt32(&g.value))
Expand All @@ -64,7 +62,7 @@ func (g *PersistentGauge) start(ctx context.Context) {
// to the metrics collector
func (g *PersistentGauge) Stop() {
g.cancel()
g.wg.Wait()
<-g.donec
}

// NewPersistentGauge will create and start a PersistentGauge that reports the current value every 10s
Expand All @@ -81,6 +79,7 @@ func NewPersistentGaugeWithDuration(name string, dur time.Duration, tags ...metr
ticker: time.NewTicker(dur),
cancel: cancel,
dur: dur,
donec: make(chan struct{}),
}
go g.start(ctx)
return &g
Expand Down
7 changes: 7 additions & 0 deletions metriks/gauge_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,13 @@ func TestPersistentGauge(t *testing.T) {
}
}

func TestPersistentGaugeRace(t *testing.T) {
for n := 0; n < 10; n++ {
g := NewPersistentGaugeWithDuration("some_gauge", time.Second, L("a", "b"))
g.Stop()
}
}

func TestScheduledGauge(t *testing.T) {
var callCount int32
cb := func() int32 {
Expand Down