"thread safe singleton in swift" Code Answer

3

thanks to @rmaddy comments which pointed me in the right direction i was able to solve the problem.

in order to make the property foo of the singleton thread safe, it need to be modified as follows:

    class singleton {

    static let shared = singleton()

    private init(){}

    private let internalqueue = dispatchqueue(label: "com.singletioninternal.queue",
                                              qos: .default,
                                              attributes: .concurrent)

    private var _foo: string = "aaa"

    var foo: string {
        get {
            return internalqueue.sync {
                _foo
            }
        }
        set (newstate) {
            internalqueue.async(flags: .barrier) {
                self._foo = newstate
            }
        }
    }

    func setup(string: string) {
        foo = string
    }
}

thread safety is accomplished by having a computed property foo which uses an internalqueue to access the "real" _foo property.

also, in order to have better performance internalqueue is created as concurrent. and it means that it is needed to add the barrier flag when writing to the property.

what the barrier flag does is to ensure that the work item will be executed when all previously scheduled work items on the queue have finished.

By Luciano Afranllie on August 1 2022

Answers related to “thread safe singleton in swift”

Only authorized users can answer the Search term. Please sign in first, or register a free account.