Skip to content

Commit

Permalink
Lock updated
Browse files Browse the repository at this point in the history
  • Loading branch information
muzahidul-opti committed Nov 29, 2023
1 parent c65e132 commit 12649cd
Showing 1 changed file with 12 additions and 12 deletions.
24 changes: 12 additions & 12 deletions Sources/Utils/AtomicProperty.swift
Original file line number Diff line number Diff line change
Expand Up @@ -21,42 +21,42 @@ class AtomicProperty<T> {
var property: T? {
get {
var retVal: T?
withLock {
lock.sync {
retVal = _property
}
return retVal
}
set {
withLock {
lock.async {
self._property = newValue
}
}
}
private let lock = NSRecursiveLock()

private let lock: DispatchQueue
init(property: T?, lock: DispatchQueue? = nil) {
self._property = property
self.lock = lock ?? {
var name = "AtomicProperty" + String(Int.random(in: 0...100000))
let className = String(describing: T.self)
name += className
return DispatchQueue(label: name, attributes: .concurrent)
}()
}

convenience init() {
self.init(property: nil, lock: nil)
}

// perform an atomic operation on the atomic property
// the operation will not run if the property is nil.
func performAtomic(atomicOperation: (_ prop:inout T) -> Void) {
withLock {
lock.sync(flags: DispatchWorkItemFlags.barrier) {
if var prop = _property {
atomicOperation(&prop)
_property = prop
}
}
}

private func withLock(callBack: () -> Void) {
lock.lock()
callBack()
lock.unlock()
}

}

0 comments on commit 12649cd

Please sign in to comment.