NSLock
public struct Cache {
private static var data = [String:Any]()
// private static var lock = DispatchSemaphore(value: 1)
private static var lock = NSLock()
public static func get(_ key:String) -> Any? {
data[key]
}
public static func set(_ key:String,_ value:Any) {
lock.lock()
defer {
lock.unlock()
}
data[key] = value
}
}
NSRecursiveLock
递归锁
public struct Cache {
private static var data = [String:Any]()
// private static var lock = DispatchSemaphore(value: 1)
// private static var lock = NSLock()
private static var lock = NSRecursiveLock()
public static func get(_ key:String) -> Any? {
data[key]
}
public static func set(_ key:String,_ value:Any) {
lock.lock()
defer {
lock.unlock()
}
data[key] = value
}
}
当发生自己调用自己的时候,或者递归的时候,需要使用递归锁NSRecursiveLock,用法跟NSLock是一样的,只是使用场景可能不一样。