From f6ff0f32a259cb5509da080bd7d637b123da5403 Mon Sep 17 00:00:00 2001 From: Aliaksandr Valialkin Date: Fri, 13 Mar 2020 12:36:02 +0200 Subject: [PATCH] fix data race when accessing h.sum during histogram marshaling --- histogram.go | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/histogram.go b/histogram.go index 3ddf687..6a72cc5 100644 --- a/histogram.go +++ b/histogram.go @@ -246,14 +246,22 @@ func (h *Histogram) marshalTo(prefix string, w io.Writer) { return } name, filters := splitMetricName(prefix) - if float64(int64(h.sum)) == h.sum { - fmt.Fprintf(w, "%s_sum%s %d\n", name, filters, int64(h.sum)) + sum := h.getSum() + if float64(int64(sum)) == sum { + fmt.Fprintf(w, "%s_sum%s %d\n", name, filters, int64(sum)) } else { - fmt.Fprintf(w, "%s_sum%s %g\n", name, filters, h.sum) + fmt.Fprintf(w, "%s_sum%s %g\n", name, filters, sum) } fmt.Fprintf(w, "%s_count%s %d\n", name, filters, countTotal) } +func (h *Histogram) getSum() float64 { + h.mu.Lock() + sum := h.sum + h.mu.Unlock() + return sum +} + func getBucketIdxAndOffset(v float64) (int, uint) { if v < 0 { panic(fmt.Errorf("BUG: v must be positive; got %g", v))