File tree Expand file tree Collapse file tree 1 file changed +30
-0
lines changed
Expand file tree Collapse file tree 1 file changed +30
-0
lines changed Original file line number Diff line number Diff line change @@ -771,3 +771,33 @@ public struct Unit: Hashable, Codable {
771771}
772772
773773public let unit = Unit ( )
774+
775+ // MARK: - Atomic
776+
777+ /// Masks `DispatchQueue`, without requiring `Foundation`.
778+ public protocol Synchronized {
779+ func sync< Output> ( execute: ( ) throws -> Output ) rethrows -> Output
780+ }
781+
782+ /// Wraps a mutable value and ensures atomic access to it.
783+ ///
784+ /// source: https://www.objc.io/blog/2018/12/18/atomic-variables/
785+ public final class Atomic < Queue: Synchronized , Wrapped> {
786+ private let queue : Queue
787+ private var value : Wrapped
788+
789+ public init ( queue: Queue , value: Wrapped ) {
790+ self . queue = queue
791+ self . value = value
792+ }
793+
794+ public var get : Wrapped {
795+ queue. sync { self . value }
796+ }
797+
798+ public func modify( _ transform: ( inout Wrapped ) -> Void ) {
799+ queue. sync {
800+ transform ( & self . value)
801+ }
802+ }
803+ }
You can’t perform that action at this time.
0 commit comments