Skip to content

Instantly share code, notes, and snippets.

@marcuswestin
Created December 28, 2019 16:33
Show Gist options
  • Save marcuswestin/507f82f040eafd8961eaecb526ad7024 to your computer and use it in GitHub Desktop.
Save marcuswestin/507f82f040eafd8961eaecb526ad7024 to your computer and use it in GitHub Desktop.
Some atomic operations in swift
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