RWLock (读写锁)

围绕 pthread_rwlock 的 Swift 封装。

详情请参阅读写锁

用法

let lock = RWLock()
lock.readProtected {
    // do something concurrently with other reads and until write lock is acquired 
}
lock.writeProtected {
    // do something that requires exclusive access
}

使用属性包装器

class Foo {
    @RWLocked var items = [Any]()
    
    func add(_ item: Any) {
        items.append(item)
    }
    
    func removeAll() {
        items.removeAll()
    }
    
    func iterate() {
        items.forEach { 
            // do something with each item
        }
    }
    
}

items 数组的任何修改都需要写保护 - 这适用于 add(_:)removeAll() 方法。 相反,迭代数组 iterate() 需要读取权限。 这意味着在迭代完成之前,您将无法 add(_:)removeAll(),并且在 add(_:)removeAll() 完成之前,您将无法 iterate()