Reader Writer Lock Implementation in Swift for multiple Properties

In my Swift class I have multiple properties. For these properties do I need to create different Concurrent Queue or I can use the same Queue?

Please suggest which one will be better.

import Foundation public class ImageCache{     public let shared = ImageCache()     private var imageFileNameDic = ["default": "default.png"]     private var notificationName = ["": "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::     } } 
Add Comment
1 Answer(s)

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]     } } 
Answered on August 31, 2020.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.