Skip to content

Commit

Permalink
fix: there is a race condition when pushing and collecting histogram …
Browse files Browse the repository at this point in the history
…data

All increment counters and the total could be changed by an other threads is preparing the cumulative data collection.
  • Loading branch information
twynantst authored and gjasny committed Oct 14, 2021
1 parent 1a66113 commit 722fbcf
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 0 deletions.
2 changes: 2 additions & 0 deletions core/include/prometheus/histogram.h
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
#pragma once

#include <mutex>
#include <vector>

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

private:
const BucketBoundaries bucket_boundaries_;
mutable std::mutex mutex_;
std::vector<Counter> bucket_counts_;
Gauge sum_;
};
Expand Down
5 changes: 5 additions & 0 deletions core/src/histogram.cc
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::mutex> lock(mutex_);
sum_.Increment(value);
bucket_counts_[bucket_index].Increment();
}
Expand All @@ -36,6 +38,7 @@ void Histogram::ObserveMultiple(const std::vector<double>& bucket_increments,
"the number of buckets in the histogram.");
}

std::lock_guard<std::mutex> lock(mutex_);
sum_.Increment(sum_of_values);

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

ClientMetric Histogram::Collect() const {
std::lock_guard<std::mutex> lock(mutex_);

auto metric = ClientMetric{};

auto cumulative_count = 0ULL;
Expand Down

0 comments on commit 722fbcf

Please sign in to comment.