Atomic property implementation with GCD.
1 2 3 4 5 6 7 8 9 10 11 12 |
fileprivate let countAtomicQueue = DispatchQueue(label: "com.dduraz.countAtomicQueue") private var _count:Int = 0 var count:Int { get { dispatchPrecondition(condition: .notOnQueue(countAtomicQueue)) return countAtomicQueue.sync { _count } } set { dispatchPrecondition(condition: .notOnQueue(countAtomicQueue)) countAtomicQueue.sync { _count = newValue } } } |
By default a DispatchQueue instantiates as a serial queue. The concept here is very simple. The count property here gets a dedicated serial queue to synchronously dispatch get and set logic. Leveraging the GCD serial queue enforces atomic behavior on the count property.
Be First to Comment