Reader-writer with a barrier: four interviewer questions
Task
A candidate wrote a thread-safe store. What does the interviewer ask next?
final class ThreadSafeStore<Key: Hashable, Value> {
private var storage: [Key: Value] = [:]
private let queue = DispatchQueue(label: "store.queue", attributes: .concurrent)
func get(_ key: Key) -> Value? {
queue.sync { storage[key] }
}
func set(_ value: Value?, for key: Key) {
queue.async(flags: .barrier) {
self.storage[key] = value
}
}
}
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep