Skip to content

Commit 63c57cf

Browse files
authored
Fix race in TraceProviderSDK (#864)
1 parent cc8fff2 commit 63c57cf

File tree

1 file changed

+7
-17
lines changed

1 file changed

+7
-17
lines changed

Sources/OpenTelemetrySdk/Trace/TracerProviderSdk.swift

Lines changed: 7 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ import Foundation
77
import OpenTelemetryApi
88

99
public class TracerProviderSdk: TracerProvider {
10-
private var tracerLock = pthread_rwlock_t()
10+
private let tracerLock: ReadWriteLock = .init()
1111
private var tracerProvider = [InstrumentationScopeInfo: TracerSdk]()
1212
var sharedState: TracerSharedState
1313
static let emptyName = "unknown"
@@ -19,7 +19,6 @@ public class TracerProviderSdk: TracerProvider {
1919
spanLimits: SpanLimits = SpanLimits(),
2020
sampler: Sampler = Samplers.parentBased(root: Samplers.alwaysOn),
2121
spanProcessors: [SpanProcessor] = []) {
22-
pthread_rwlock_init(&tracerLock, nil)
2322
sharedState = TracerSharedState(clock: clock,
2423
idGenerator: idGenerator,
2524
resource: resource,
@@ -28,10 +27,6 @@ public class TracerProviderSdk: TracerProvider {
2827
spanProcessors: spanProcessors)
2928
}
3029

31-
deinit {
32-
pthread_rwlock_destroy(&tracerLock)
33-
}
34-
3530
public func get(instrumentationName: String, instrumentationVersion: String? = nil, schemaUrl: String? = nil, attributes: [String: AttributeValue]? = nil) -> Tracer {
3631
if sharedState.hasBeenShutdown {
3732
return DefaultTracer.instance
@@ -50,22 +45,17 @@ public class TracerProviderSdk: TracerProvider {
5045
attributes: attributes
5146
)
5247

53-
if pthread_rwlock_rdlock(&tracerLock) == 0 {
54-
let existingTracer = tracerProvider[instrumentationScopeInfo]
55-
pthread_rwlock_unlock(&tracerLock)
56-
57-
if existingTracer != nil {
58-
return existingTracer!
59-
}
48+
let existingTracer = tracerLock.withReaderLock {
49+
tracerProvider[instrumentationScopeInfo]
50+
}
51+
if let existingTracer {
52+
return existingTracer
6053
}
6154

6255
let tracer = TracerSdk(sharedState: sharedState, instrumentationScopeInfo: instrumentationScopeInfo)
63-
64-
if pthread_rwlock_wrlock(&tracerLock) == 0 {
56+
tracerLock.withWriterLock {
6557
tracerProvider[instrumentationScopeInfo] = tracer
66-
pthread_rwlock_unlock(&tracerLock)
6758
}
68-
6959
return tracer
7060
}
7161

0 commit comments

Comments
 (0)