我的 A类具有B类的属性,可以重置:
class A1 {
private var b = B(0)
func changeB(i : Int) {
b = B(i)
}
func testB(k : Int) -> Bool {
return b.test(k)
}
}
class B {
private let b : Int;
init(_ i : Int) {
b = i
}
func test(_ k : Int) -> Bool {
return b == k
}
}
到目前为止,一切都很好。如果我想在多线程场景中使用A类,我必须添加一些同步机制,因为 Swift中的属性本身不是原子的:
class A2 {
private var b = B(0)
private let lock = NSLock()
func changeB(i : Int) {
lock.lock()
defer { lock.unlock() }
b = B(i)
}
func testB(k : Int) -> Bool {
lock.lock()
defer { lock.unlock() }
return b.test(k)
}
}
但现在我想介绍一个闭包:
class A3 {
func listenToB() {
NotificationCenter.default.addObserver(forName: Notification.Name("B"), object: nil, queue: nil) {
[b] (notification) in
let k = notification.userInfo!["k"] as! Int
print(b.test(k))
}
}
}
我是否正确理解这不是线程安全的?如果我也捕获,这会得到解决lock
吗,如下所示?
class A4 {
func listenToB() {
NotificationCenter.default.addObserver(forName: Notification.Name("B"), object: nil, queue: nil) {
[lock, b] (notification) in
let k = notification.userInfo!["k"] as! Int
lock.lock()
defer { lock.unlock() }
print(b.test(k))
}
}
}