Skip to content

Commit 722fbcf

Browse files
twynantstgjasny
authored andcommitted
fix: there is a race condition when pushing and collecting histogram data
All increment counters and the total could be changed by an other threads is preparing the cumulative data collection.
1 parent 1a66113 commit 722fbcf

File tree

2 files changed

+7
-0
lines changed

2 files changed

+7
-0
lines changed

core/include/prometheus/histogram.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#pragma once
22

3+
#include <mutex>
34
#include <vector>
45

56
#include "prometheus/client_metric.h"
@@ -68,6 +69,7 @@ class PROMETHEUS_CPP_CORE_EXPORT Histogram {
6869

6970
private:
7071
const BucketBoundaries bucket_boundaries_;
72+
mutable std::mutex mutex_;
7173
std::vector<Counter> bucket_counts_;
7274
Gauge sum_;
7375
};

core/src/histogram.cc

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,8 @@ void Histogram::Observe(const double value) {
2424
std::find_if(
2525
std::begin(bucket_boundaries_), std::end(bucket_boundaries_),
2626
[value](const double boundary) { return boundary >= value; })));
27+
28+
std::lock_guard<std::mutex> lock(mutex_);
2729
sum_.Increment(value);
2830
bucket_counts_[bucket_index].Increment();
2931
}
@@ -36,6 +38,7 @@ void Histogram::ObserveMultiple(const std::vector<double>& bucket_increments,
3638
"the number of buckets in the histogram.");
3739
}
3840

41+
std::lock_guard<std::mutex> lock(mutex_);
3942
sum_.Increment(sum_of_values);
4043

4144
for (std::size_t i{0}; i < bucket_counts_.size(); ++i) {
@@ -44,6 +47,8 @@ void Histogram::ObserveMultiple(const std::vector<double>& bucket_increments,
4447
}
4548

4649
ClientMetric Histogram::Collect() const {
50+
std::lock_guard<std::mutex> lock(mutex_);
51+
4752
auto metric = ClientMetric{};
4853

4954
auto cumulative_count = 0ULL;

0 commit comments

Comments
 (0)