diff --git a/core/include/prometheus/histogram.h b/core/include/prometheus/histogram.h index f8be2435..a26f8432 100644 --- a/core/include/prometheus/histogram.h +++ b/core/include/prometheus/histogram.h @@ -1,5 +1,6 @@ #pragma once +#include #include #include "prometheus/client_metric.h" @@ -68,6 +69,7 @@ class PROMETHEUS_CPP_CORE_EXPORT Histogram { private: const BucketBoundaries bucket_boundaries_; + mutable std::mutex mutex_; std::vector bucket_counts_; Gauge sum_; }; diff --git a/core/src/histogram.cc b/core/src/histogram.cc index 78ba3c88..4947b3a7 100644 --- a/core/src/histogram.cc +++ b/core/src/histogram.cc @@ -24,6 +24,8 @@ void Histogram::Observe(const double value) { std::find_if( std::begin(bucket_boundaries_), std::end(bucket_boundaries_), [value](const double boundary) { return boundary >= value; }))); + + std::lock_guard lock(mutex_); sum_.Increment(value); bucket_counts_[bucket_index].Increment(); } @@ -36,6 +38,7 @@ void Histogram::ObserveMultiple(const std::vector& bucket_increments, "the number of buckets in the histogram."); } + std::lock_guard lock(mutex_); sum_.Increment(sum_of_values); for (std::size_t i{0}; i < bucket_counts_.size(); ++i) { @@ -44,6 +47,8 @@ void Histogram::ObserveMultiple(const std::vector& bucket_increments, } ClientMetric Histogram::Collect() const { + std::lock_guard lock(mutex_); + auto metric = ClientMetric{}; auto cumulative_count = 0ULL;