how\'d you apply thread safe functionality to static functions of a struct
class SingleSome {
struct Static {
private static var instance: Singl
You can use a private serial queue to ensure that only one thread can be in any of the critical sections at any instant.
class SingleSome {
struct Static {
private static let queue = dispatch_queue_create("SingleSome.Static.queue", nil)
private static var instance: SingleSome?
static func getInstance(block: () -> SingleSome) -> SingleSome {
var myInstance: SingleSome?
dispatch_sync(queue) {
if self.instance == nil {
self.instance = block()
}
myInstance = self.instance
}
// This return has to be outside the dispatch_sync block,
// so there's a race condition if I return instance directly.
return myInstance!
}
static func remove() {
dispatch_sync(queue) {
self.instance = nil
}
}
}
}