how\'d you apply thread safe functionality to static functions of a struct
class SingleSome {
struct Static {
private static var instance: Singl
Use a semaphore, dispatch_sync isn't appropriate because you need a synchronous return value from getInstance:
class SingleSome {
struct Static {
private static var instance: SingleSome?
private static let lock = dispatch_semaphore_create(1)
//need barrier sync
static func getInstance(block: () -> SingleSome) -> SingleSome {
dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER)
var value = instance
if value == nil {
instance = block()
value = instance
}
dispatch_semaphore_signal(lock)
return value!
}
static func remove() { //need barrier sync
dispatch_semaphore_wait(lock, DISPATCH_TIME_FOREVER)
instance = nil
dispatch_semaphore_signal(lock)
}
}
}
Also note that as written this is subject to deadlocks if block results in either remove or getInstance being called as dispatch_semaphore_t is not thread recursive.