Skip to content

Instantly share code, notes, and snippets.

@ole ole/Atomic.swift
Created Jun 6, 2019

Embed
What would you like to do?
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
You can’t perform that action at this time.