Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 14 additions & 17 deletions Sources/Segment/Utilities/Atomic.swift
Original file line number Diff line number Diff line change
Expand Up @@ -7,29 +7,26 @@

import Foundation

// NOTE: Revised from previous implementation which used a struct and NSLock's.
// Thread Sanitizer was *correctly* capturing this issue, which was a little obscure
// given the property wrapper PLUS the semantics of a struct. Moving to `class`
// removes the semantics problem and lets TSan approve of what's happening.
//
// Additionally, moving to a lock free version is just desirable, so moved to a queue.
//
// Also see thread here: https://github.com/apple/swift-evolution/pull/1387

@propertyWrapper
public struct Atomic<T> {
var value: T
private let lock = NSLock()
public class Atomic<T> {
private var value: T
private let queue = DispatchQueue(label: "com.segment.atomic.\(UUID().uuidString)")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice 👍


public init(wrappedValue value: T) {
self.value = value
}

public var wrappedValue: T {
get { return load() }
set { store(newValue: newValue) }
}

func load() -> T {
lock.lock()
defer { lock.unlock() }
return value
}

mutating func store(newValue: T) {
lock.lock()
defer { lock.unlock() }
value = newValue
get { return queue.sync { return value } }
set { queue.sync { value = newValue } }
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import Foundation
public class CountBasedFlushPolicy: FlushPolicy {
public weak var analytics: Analytics?
internal var desiredCount: Int?
internal var count: Int = 0
@Atomic internal var count: Int = 0

init() { }

Expand Down