gpt4 book ai didi

ios - Swift:使用 NSLock 或并发队列的安全线程

转载 作者:行者123 更新时间:2023-12-03 08:29:26 24 4
gpt4 key购买 nike

最好的方法是什么Safe Thread

使用NSLock :

class Observable<T> {

typealias Observer = (_ observable: Observable<T>, T) -> Void

private var observers: [Observer]
private let lock = NSLock()
private var _value: T

var value: T {
get {
lock.lock()
let value = _value
lock.unlock()
return value
}
set {
lock.lock()
_value = newValue
lock.unlock()
}
}


init(_ value: T) {
self._value = value
observers = []
}

func observe(observer: @escaping Observer) {
self.observers.append((observer))
}

private func notifyObservers(_ value: T) {
DispatchQueue.main.async {
self.observers.forEach { [unowned self](observer) in
observer(self, value)
}
}
}

}

使用Queue :

class SecondObservable<T> {

typealias Observer = (_ observable: SecondObservable<T>, T) -> Void

private var observers: [Observer]
private let safeQueue = DispatchQueue(label: "com.observable.value", attributes: .concurrent)
private var _value: T

var value: T {
get {
var value: T!
safeQueue.sync { value = _value }
return value
}
set {
safeQueue.async(flags: .barrier) { self._value = newValue }
}
}


init(_ value: T) {
self._value = value
observers = []
}

func observe(observer: @escaping Observer) {
self.observers.append((observer))
}

private func notifyObservers(_ value: T) {
DispatchQueue.main.async {
self.observers.forEach { [unowned self](observer) in
observer(self, value)
}
}
}

}

或者序列号Queue :

class ThirdObservable<T> {

typealias Observer = (_ observable: ThirdObservable<T>, T) -> Void

private var observers: [Observer]
private let safeQueue = DispatchQueue(label: "com.observable.value")
private var _value: T

var value: T {
get {
var value: T!
safeQueue.async { value = self._value }
return value
}
set {
safeQueue.async { self._value = newValue }
}
}


init(_ value: T) {
self._value = value
observers = []
}

func observe(observer: @escaping Observer) {
self.observers.append((observer))
}

private func notifyObservers(_ value: T) {
DispatchQueue.main.async {
self.observers.forEach { [unowned self](observer) in
observer(self, value)
}
}
}

}

NSLockQueue.concurrent上述案例的属性,为什么?

最佳答案

在这种情况下,带有 barrier 标志的并发队列比使用 NSLock 更高效。

当 setter 运行时,它们都会阻止其他操作,但区别在于并发或并行调用多个 getter 时。

  • NSLock:仅允许 1 个 getter 一次运行
  • 带有 barrier 标志的并发队列:允许同时运行多个 getter

关于ios - Swift:使用 NSLock 或并发队列的安全线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65574904/

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