# Singleton lock for a queue

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 {

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
}
}

• Please also explain how this code is intended to be used. – 200_success Oct 12 '17 at 19:20