Skip to content

Instantly share code, notes, and snippets.

@aainaj
Created June 2, 2020 04:41
Show Gist options
  • Save aainaj/1c86a831dbfe04584fc13bf56b821f90 to your computer and use it in GitHub Desktop.
Save aainaj/1c86a831dbfe04584fc13bf56b821f90 to your computer and use it in GitHub Desktop.
ThreadSafe Singleton
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