Created
March 7, 2019 09:33
-
-
Save smosko/af7b4914f5ee87089938a5756a3a41f6 to your computer and use it in GitHub Desktop.
Atomic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
https://www.objc.io/blog/2018/12/18/atomic-variables/
https://www.objc.io/blog/2019/01/15/atomic-variables-part-2/
https://github.com/radianttap/Swift-Essentials/blob/master/Sources/Atomic.swift