Xcode Incorrectly Reporting Swift Access Race Condition

后端 未结 1 1118
南笙
南笙 2021-01-03 07:53

I believe XCode is incorrectly reporting Swift Access Race in my SynchronizedDictionary - or is it?

My SynchronizedDictionary looks like th

相关标签:
1条回答
  • 2021-01-03 08:47

    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.

    0 讨论(0)
提交回复
热议问题