Created
June 2, 2020 04:41
-
-
Save aainaj/1c86a831dbfe04584fc13bf56b821f90 to your computer and use it in GitHub Desktop.
ThreadSafe Singleton
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
final class FeaturedTopics { | |
private let concurrentQueue = DispatchQueue(label: "concurrentQueue", attributes: .concurrent) | |
private var topics: [String: Any] = [:] | |
static let shared = FeaturedTopics() | |
private init() {} | |
subscript(key: String) -> Any? { | |
get { | |
var topic: Any? | |
// conocurrent queue allows executing read operations in parallel | |
concurrentQueue.sync { | |
topic = self.topics[key] | |
} | |
return topic | |
} | |
set { | |
// barrier turns concurrent queue into serial queue temporarily | |
// As a result no other thread can modify internal dictionary while this block is executing | |
concurrentQueue.async(flags: .barrier) { | |
self.topics[key] = newValue | |
} | |
} | |
} | |
func reset() { | |
topics.removeAll() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment