1
\$\begingroup\$

This is a singleton class which can be accessed anywhere including the shouldLock variable. I want to make sure that the variable is thread safe. Basically the shouldLock is used to keep track if the user is allowed to use any other view controllers, unless they provide a password, in the app.

Is this the proper way to make a variable thread safe? Is there an easier or better way? I got my inspiration from here.

class LockNavigation {
    static var shared = LockNavigation()

    let queue = DispatchQueue(label: "LockNavigationQueue", attributes: .concurrent)

    var _shouldLock:Bool!
    var shouldLock:Bool{
        get{
            var copy:Bool!
            queue.sync(flags: .barrier) {
                copy = _shouldLock
            }
            return copy
        }

        set{
            queue.async(flags: .barrier) {
                self._shouldLock = newValue
            }
        }
    }

    private init() {
        shouldLock = false
    }
}
\$\endgroup\$
  • 1
    \$\begingroup\$ Please also explain how this code is intended to be used. \$\endgroup\$ – 200_success Oct 12 '17 at 19:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.