Search code examples
performancethread-safetygrand-central-dispatchsynchronizationios-multithreading

Does synchronising a class property in setter - getter for thread safety impact performance?


I have a race condition in a class property. One thread is reading it on another is writing. Now i have come up with a solution to synchronise getter and setter of that property. The question is will this impact the performance of the application? If yes, is there any solution other than synchronising the property ?


Solution

  • Synchronisation will always have an impact on performance, but how much of an impact is entirely dependant on the individual case - e.g. how often is the setter called compared to the getter, how fast is the setter call compared to the getter, etc.

    In Swift, you can use a DispatchQueue with a .barrier flag to implement a readers-writer lock:

    class MyClass {
        private static let queue = DispatchQueue(
            label: "synchronisation",
            qos: .userInitiated, // use QoS that match your current use-case
            attributes: [.concurrent]
        )
        private static var _field = ""
        public static var field: String {
            get {
                return queue.sync {
                    return self._field
                }
            }
            set {
                return queue.sync(flags: .barrier) {
                    self._field = newValue
                }
            }
        }
    }
    

    On the other hand, synchronisation is the only way to correctly handle concurrent access to the same "resource".