如何将线程安全功能应用于结构的静态函数
class SingleSome {
struct Static {
private static var instance: SingleSome?
//need barrier sync
static func getInstance(block: () -> SingleSome) -> SingleSome {
if instance == nil {
instance = block()
}
return instance!
}
static func remove() { //need barrier sync
instance = nil
}
}
}
因为可能存在SingleSome
答案 0 :(得分:3)
您可以使用专用串行队列来确保任何时刻只有一个线程可以位于任何关键部分。
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
}
}
}
}
答案 1 :(得分:0)
使用信号量,dispatch_sync不合适,因为你需要来自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)
}
}
}
另请注意,如果写入此块会导致死锁,如果由于dispatch_semaphore_t不是线程递归而导致remove或getInstance被调用。