0

在我的Swift课堂上,我有多个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::
    }
}
4

1 回答 1

1

If they’re independent properties in low-contention environment, it doesn’t matter too much. If you use one queue, it just means you can’t update one while updating the other. Whereas if you use separate queues, you’re synchronizing them separately.


By the way, you can simplify your readers, e.g.

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

Or in recent Swift versions:

public func getImageFileName(forKey key: String) -> String? {
    concurrentQueue.sync {
        self.imageFileNameDic[key]
    }
}
于 2020-08-28T07:57:07.590 回答