Skip to content

Instantly share code, notes, and snippets.

@smosko
Created March 7, 2019 09:33
Show Gist options
  • Save smosko/af7b4914f5ee87089938a5756a3a41f6 to your computer and use it in GitHub Desktop.
Save smosko/af7b4914f5ee87089938a5756a3a41f6 to your computer and use it in GitHub Desktop.
Atomic
import Dispatch
public final class Atomic<A> {
private var _value: A
private let queue: DispatchQueue
public init(_ value: A, targetQueue: DispatchQueue? = nil) {
_value = value
queue = DispatchQueue(label: "Atomic", attributes: .concurrent, target: targetQueue)
}
public var value: A {
return queue.sync { _value }
}
public func mutate(_ transform: (inout A) -> Void) {
queue.sync(flags: .barrier) {
transform(&_value)
}
}
}
extension Atomic: Equatable where A: Equatable {
public static func ==(lhs: Atomic, rhs: Atomic) -> Bool {
return lhs.value == rhs.value
}
}
extension Atomic: Hashable where A: Hashable {
public func hash(into hasher: inout Hasher) {
hasher.combine(value)
}
}