Thread protection for getter and setter in single point

I created a simple singleton in Swift 3:

class MySingleton {
    private var myName: String
    private init() {}
    static let shared = MySingleton()

    func setName(_ name: String) {
        myName = name
    }

    func getName() -> String {
        return myName
    }
}

Since I made init()private and also declared an sharedinstance static let, I think the initializer is thread safe. But what about the getter and setter functions for myName, are they safe?

+5
source share
2 answers

You are right that the recipients you wrote are not thread safe. In Swift, the easiest (most secure) way to achieve this at the moment is to use Grand Central Dispatch queues as a locking mechanism. The easiest (and easiest way) is to reach the base sequential queue.

class MySingleton {

    static let shared = MySingleton()

    // Serial dispatch queue
    private let lockQueue = DispatchQueue(label: "MySingleton.lockQueue")

    private var _name: String
    var name: String {
        get {
            return lockQueue.sync {
                return _name
            }
        }

        set {
            lockQueue.sync {
                _name = newValue
            }
        }
    }

    private init() {
        _name = "initial name"
    }
}

, , "" . . sync , , , .

. , . , , .

: https://mikeash.com/pyblog/friday-qa-2015-02-06-locks-thread-safety-and-swift.html Swift, Objective-C 's synchronized "?

+7

( Xcode 9) - , .

final class MySingleton {
    static let shared = MySingleton()

    private let nameQueue = DispatchQueue(label: "name.accessor", qos: .default, attributes: .concurrent)
    private var _name = "Initial name"

    private init() {}

    var name: String {
        get {
            var name = ""
            nameQueue.sync {
                name = _name
            }

            return name
        }
        set {
            nameQueue.async(flags: .barrier) {
                self._name = newValue
            }
        }
    }
}
  • , . , , ...
  • .barrier. , , , . , . , , . , , . , . , . , , , , .
+5

All Articles