Reader Swift 中多个属性的写入器锁定实现

Reader Writer Lock Implementation in Swift for multiple Properties

在我的 Swift class 我有多个 properties。对于这些属性,我需要创建不同的 Concurrent Queue 还是可以使用相同的队列?

请建议哪个更好。

import Foundation
public class ImageCache{
    public let shared = ImageCache()
    private var imageFileNameDic = ["default": "default.png"]
    private var notificationName = ["default.pn": "default-noti"]
    //More properties will be here...
    private let concurrentQueue = DispatchQueue(label: "conCurrentQueue", attributes: .concurrent)

    public func setImageFileName(value: String, forKey key: String) {
        concurrentQueue.async(flags: .barrier){
            self.imageFileNameDic[key] = value
        }
    }

    public func getImageFileName(forKey key: String) -> String? {
        var result: String?
        concurrentQueue.sync {
            result = self.imageFileNameDic[key]
        }
        return result
    }

    //For notificationName dictionary do i need to declare another
    //Queue or use the same Queue
    public func setNotificationName(value: String, forKey key: String) {
        //TODO::
    }
    public func getNotificationName(forKey key: String) {
        //TODO::
    }
}

如果它们在low-contention环境中是独立的属性,那就无所谓了。如果您使用一个队列,则意味着您不能在更新另一个的同时更新一个。而如果您使用单独的队列,您将分别同步它们。


顺便说一句,你可以简化你的读者,例如

public func getImageFileName(forKey key: String) -> String? {
    return concurrentQueue.sync {
        return self.imageFileNameDic[key]
    }
}

或最近 Swift 个版本:

public func getImageFileName(forKey key: String) -> String? {
    concurrentQueue.sync {
        self.imageFileNameDic[key]
    }
}