I believe XCode is incorrectly reporting Swift Access Race in my SynchronizedDictionary
- or is it?
My SynchronizedDictionary
looks like th
The thread sanitizer reports a Swift access race to the
var syncDict = SynchronizedDictionary<String, String>()
structure, because there is a mutating access (via the subscript setter) at
syncDict["\(i)"] = "\(i)"
from one thread, and a read-only access to the same structure (via the subscript getter) at
_ = syncDict["\(i)"]
from a different thread, without synchronization.
This has nothing to do with conflicting access to the private var dictionary
property, or with what happens inside the subscript methods at all. You'll get the same “Swift access race” if you simplify the structure to
public struct SynchronizedDictionary<K: Hashable, V> {
private let dummy = 1
public subscript(key: String) -> String {
get {
return key
}
set {
}
}
}
So this is a correct report from the thread sanitizer, not a bug.
A possible solution would be to define a class instead:
public class SynchronizedDictionary<K: Hashable, V> { ... }
That is a reference type and the subscript setter no longer mutates the syncDict
variable (which is now a “pointer” into the actual object storage). With that change, your code runs without errors.