Junior — Senior
Detecting issues in the provided Swift code
livecode
Task condition
In this example, a service for storing pairs of "identifier – name" is implemented. The PersonRegistry class provides methods for adding, removing, and retrieving values by key. Then, several tasks simultaneously add and remove entries in a shared dictionary, as well as read from it. Since access to the shared collection occurs from different threads without any synchronization, the code is susceptible to data races and potential failures. Below is the original code with renamed variables.
class PersonRegistry {
private var storage = [String: String]()
func insert(value: String, for key: String) {
storage[key] = value
}
func delete(key: String) {
storage[key] = nil
}
func fetch(key: String) -> String? {
return storage[key]
}
}
let registry = PersonRegistry()
let workQueue = DispatchQueue(label: "Work Queue", attributes: .concurrent)
for i in 0..<1000 {
let id = String(describing: i)
let name = String(describing: i)
workQueue.async {
registry.insert(value: name, for: id)
}
workQueue.async {
registry.delete(key: id)
}
}
workQueue.async {
for i in 0..<1000 {
let id = String(describing: i)
_ = registry.fetch(key: id)
}
}