Skip to content

Commit b217e33

Browse files
committed
Synchronize access race in HistogramMetric
1 parent 4d973a1 commit b217e33

File tree

2 files changed

+21
-11
lines changed

2 files changed

+21
-11
lines changed

Sources/OpenTelemetrySdk/Metrics/HistogramMetricSdk.swift

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,24 @@ internal class HistogramMetricSdk<T: SignedNumeric & Comparable>: HistogramMetri
1010
public private(set) var boundInstruments = [LabelSet: BoundHistogramMetricSdkBase<T>]()
1111
let metricName: String
1212
let explicitBoundaries: Array<T>?
13+
let bindUnbindLock = Lock()
1314

1415
init(name: String, explicitBoundaries: Array<T>? = nil) {
1516
metricName = name
1617
self.explicitBoundaries = explicitBoundaries
1718
}
1819

1920
func bind(labelset: LabelSet) -> BoundHistogramMetric<T> {
20-
var boundInstrument = boundInstruments[labelset]
21-
if boundInstrument == nil {
22-
boundInstrument = createMetric()
23-
boundInstruments[labelset] = boundInstrument!
21+
var boundInstrument: BoundHistogramMetricSdkBase<T>?
22+
23+
bindUnbindLock.withLock {
24+
var boundInstrument = boundInstruments[labelset]
25+
if boundInstrument == nil {
26+
boundInstrument = createMetric()
27+
boundInstruments[labelset] = boundInstrument!
28+
}
2429
}
30+
2531
return boundInstrument!
2632
}
2733

Sources/OpenTelemetrySdk/Metrics/MeterSdk.swift

Lines changed: 11 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -194,14 +194,18 @@ class MeterSdk: Meter {
194194
let metricName = histogram.key
195195
let measureInstrument = histogram.value
196196
var metric = Metric(namespace: meterName, name: metricName, desc: meterName + metricName, type: AggregationType.doubleHistogram, resource: resource, instrumentationScopeInfo: instrumentationScopeInfo)
197-
measureInstrument.boundInstruments.forEach { boundInstrument in
198-
let labelSet = boundInstrument.key
199-
let aggregator = boundInstrument.value.getAggregator()
200-
aggregator.checkpoint()
201-
var metricData = aggregator.toMetricData()
202-
metricData.labels = labelSet.labels
203-
metric.data.append(metricData)
197+
198+
measureInstrument.bindUnbindLock.withLock {
199+
measureInstrument.boundInstruments.forEach { boundInstrument in
200+
let labelSet = boundInstrument.key
201+
let aggregator = boundInstrument.value.getAggregator()
202+
aggregator.checkpoint()
203+
var metricData = aggregator.toMetricData()
204+
metricData.labels = labelSet.labels
205+
metric.data.append(metricData)
206+
}
204207
}
208+
205209
metricProcessor.process(metric: metric)
206210
}
207211

0 commit comments

Comments
 (0)