Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

sampler data race fix #4004

Merged
merged 2 commits into from
Jul 10, 2023
Merged
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
14 changes: 10 additions & 4 deletions executor/resources/sampler.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ type WithTimestamp interface {
}

type Sampler[T WithTimestamp] struct {
mu sync.RWMutex
mu sync.Mutex
minInterval time.Duration
maxSamples int
callback func(ts time.Time) (T, error)
Expand All @@ -32,9 +32,9 @@ type Sub[T WithTimestamp] struct {
func (s *Sub[T]) Close(captureLast bool) ([]T, error) {
s.sampler.mu.Lock()
delete(s.sampler.subs, s)
s.sampler.mu.Unlock()

if s.err != nil {
s.sampler.mu.Unlock()
return nil, s.err
}
current := s.first
Expand All @@ -46,6 +46,7 @@ func (s *Sub[T]) Close(captureLast bool) ([]T, error) {
current = ts
}
}
s.sampler.mu.Unlock()

if captureLast {
v, err := s.sampler.callback(time.Now())
Expand Down Expand Up @@ -94,22 +95,26 @@ func (s *Sampler[T]) run() {
return
case <-ticker.C:
tm := time.Now()
s.mu.Lock()
active := make([]*Sub[T], 0, len(s.subs))
s.mu.RLock()
for ss := range s.subs {
if tm.Sub(ss.last) < ss.interval {
continue
alexcb marked this conversation as resolved.
Show resolved Hide resolved
}
ss.last = tm
active = append(active, ss)
}
s.mu.RUnlock()
s.mu.Unlock()
ticker = time.NewTimer(s.minInterval)
if len(active) == 0 {
continue
}
value, err := s.callback(tm)
s.mu.Lock()
for _, ss := range active {
if _, found := s.subs[ss]; !found {
continue // skip if Close() was called while the lock was released
}
if err != nil {
ss.err = err
} else {
Expand All @@ -121,6 +126,7 @@ func (s *Sampler[T]) run() {
ss.interval *= 2
}
}
s.mu.Unlock()
}
}
}
Expand Down
Loading