Skip to content

Commit 87cd434

Browse files
committed
Some more race condition fix
1 parent 06107be commit 87cd434

File tree

1 file changed

+12
-12
lines changed

1 file changed

+12
-12
lines changed

scope.go

Lines changed: 12 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -90,6 +90,7 @@ type scope struct {
9090

9191
histogramsSlice []*histogram
9292
histogramsSliceMux sync.Mutex
93+
clearMux sync.Mutex // Protects clearMetrics operations
9394

9495
// timersSlice is deliberately skipped. No dedicated mux for it for now.
9596

@@ -297,7 +298,7 @@ func (s *scope) reportLoop(interval time.Duration) {
297298
}
298299

299300
func (s *scope) reportLoopRun() {
300-
if s.closed != 0 {
301+
if atomic.LoadInt32(&s.closed) != 0 {
301302
return
302303
}
303304

@@ -508,7 +509,12 @@ func (s *scope) subscope(prefix string, tags map[string]string) Scope {
508509
if s.registry != nil && s.registry.root != nil && s.registry.root.baseReporter != nil {
509510
// Check if NoCacheSubscopes option is enabled on the root scope
510511
if s.noCacheSubscopes {
511-
allTags := mergeRightTagsPooled(s.tags, s.copyAndSanitizeMap(tags))
512+
pooledTags := mergeRightTagsPooled(s.tags, s.copyAndSanitizeMap(tags))
513+
allTags := make(map[string]string, len(pooledTags))
514+
for k, v := range pooledTags {
515+
allTags[k] = v
516+
}
517+
releaseTagMap(&pooledTags)
512518

513519
// Create ephemeral scope with sync.Map instead of map[string]*timer
514520
ephemeralScope := &scope{
@@ -675,6 +681,9 @@ func (s *scope) Close() error {
675681
}
676682

677683
func (s *scope) clearMetrics() {
684+
s.clearMux.Lock()
685+
defer s.clearMux.Unlock()
686+
678687
s.counters.Range(func(key, value interface{}) bool {
679688
s.counters.Delete(key)
680689
return true
@@ -848,16 +857,7 @@ func mergeRightTagsPooled(tagsLeft, tagsRight map[string]string) map[string]stri
848857
result[k] = v
849858
}
850859

851-
// Create a new map to return (since we need to return the pooled one)
852-
finalResult := make(map[string]string, len(result))
853-
for k, v := range result {
854-
finalResult[k] = v
855-
}
856-
857-
// Return the pooled map for reuse
858-
releaseTagMap(resultPtr)
859-
860-
return finalResult
860+
return result
861861
}
862862

863863
type snapshot struct {

0 commit comments

Comments
 (0)