美文网首页
Swift 中安全加锁的代码逻辑

Swift 中安全加锁的代码逻辑

作者: MiniCoder | 来源:发表于2020-03-15 19:16 被阅读0次
    final public class UnfairLock {
        private let unfairLock: os_unfair_lock_t
    
        public init() {
            
            unfairLock = .allocate(capacity: 1)
            unfairLock.initialize(to: os_unfair_lock())
        }
    
        deinit {
            unfairLock.deinitialize(count: 1)
            unfairLock.deallocate()
        }
    
        private func lock() {
            os_unfair_lock_lock(unfairLock)
        }
    
        private func unlock() {
            os_unfair_lock_unlock(unfairLock)
        }
    
    
        public func around<T>(_ closure: () throws -> T) rethrows -> T {
            lock(); defer { unlock() }
            return try closure()
        }
    
        public func around(_ closure: () throws -> Void) rethrows -> Void {
            lock(); defer { unlock() }
            return try closure()
        }
    }
    
    

    相关文章

      网友评论

          本文标题:Swift 中安全加锁的代码逻辑

          本文链接:https://www.haomeiwen.com/subject/sjsmehtx.html