Created
December 28, 2019 16:33
-
-
Save marcuswestin/507f82f040eafd8961eaecb526ad7024 to your computer and use it in GitHub Desktop.
Some atomic operations in swift
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 Foundation | |
final class Atomic {} | |
extension Atomic { | |
// Atomic value example: | |
// let val = Atomic.Value<Int>(1) | |
// val.mutate { $0 += 1 } | |
// val.get() | |
final class Value<T> { | |
private let _queue = SerialQueue() | |
private var _value: T | |
init(_ value: T) { | |
_value = value | |
} | |
func get() -> T { | |
return _queue.doSeriallyWithResult { _value } | |
} | |
typealias UpdateBlock = (inout T) -> () | |
func update(_ updateBlock: UpdateBlock) { | |
_queue.doSerially { | |
updateBlock(&_value) | |
} | |
} | |
} | |
} | |
extension Atomic { | |
final class SerialQueue { | |
private let _queue = DispatchQueue(label: "Atomic.SerialQueue") | |
func doSeriallyWithResult<T>(_ block: () -> T) -> T { | |
return _queue.sync(execute: block) | |
} | |
func doSerially(_ block: () -> Void) { | |
_queue.sync(execute: block) | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment