Skip to content

Instantly share code, notes, and snippets.

@ole
Created June 6, 2019 13:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ole/f9407843fde7773ecce44c67dcf31978 to your computer and use it in GitHub Desktop.
Save ole/f9407843fde7773ecce44c67dcf31978 to your computer and use it in GitHub Desktop.
Atomic as a property wrapper
import Dispatch
import PlaygroundSupport
@propertyDelegate
struct Atomic<A> {
private var _value: A
private let queue = DispatchQueue(label: "property wrapper")
init(initialValue: A) {
_value = initialValue
}
var value: A {
queue.sync { _value }
}
mutating func mutate(_ transform: (inout A) -> Void) {
queue.sync {
transform(&_value)
}
}
}
class C {
@Atomic var counter: Int = 0
func hammer() {
DispatchQueue.concurrentPerform(iterations: 1000) { _ in
$counter.mutate { $0 += 1 }
}
}
}
PlaygroundPage.current.needsIndefiniteExecution = true
let c = C()
c.hammer()
c.$counter
print(c.counter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment