Created
June 6, 2019 13:27
-
-
Save ole/f9407843fde7773ecce44c67dcf31978 to your computer and use it in GitHub Desktop.
Atomic as a property wrapper
This file contains hidden or 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 | |
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