gpt4 book ai didi

swift - 具有结构静态函数的 GCD

转载 作者:可可西里 更新时间:2023-11-01 01:06:27 25 4
gpt4 key购买 nike

如何将线程安全功能应用于结构的静态函数

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

}

原因是一个 block 被用作参数,因为可能有 SingleSome 的继承对象

最佳答案

您可以使用私有(private)串行队列来确保在任何时刻只有一个线程可以处于任何临界区。

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

}

关于swift - 具有结构静态函数的 GCD,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27839595/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com