在Swift中创建线程安全读取时,为什么在并发队列之外创建变量? [英] When creating thread safe reads in Swift, why is a variable create outside the concurrent queue?
问题描述
public class Account {
// MARK: Initializer
// Custom initializer
// MARK: Stored Properties
let concurrentQueue: DispatchQueue = DispatchQueue(
label: "concurrentQueue",
qos: DispatchQoS.userInitiated,
attributes: [DispatchQueue.Attributes.concurrent]
)
private var _name: String
public name: String {
get {
return self.concurrentQueue.sync { return self._name }
}
set {
self.concurrentQueue.async(flags: .barrier) {
self._name = newValue
}
}
}
}
假设您有一个像上面这样的类,您需要线程安全.
Let's say you have a class like above where you want thread safety.
Account
类中的吸气剂与这样定义吸气剂有什么区别?
What is the difference between the getter in the Account
class and defining the getter like this?
get {
var result: String!
self.concurrentQueue.sync { result = self._name }
return result
}
我目前正在全神贯注于线程安全,并且我总是看到像后者那样创建读取.在我看来,它们几乎是相同的...我错了吗?
I'm currently wrapping my head around thread safety and I always see reads created like the latter. It seems to me they're virtually the same... am I wrong?
来源: GCD教程
推荐答案
没有区别.有两种DispatchQueue.sync
方法:
There is no difference. There are two DispatchQueue.sync
methods:
public func sync(execute block: () -> Swift.Void)
public func sync<T>(execute work: () throws -> T) rethrows -> T
,在您的第一个示例中,使用了第二个示例:闭包可以返回一个值,然后该值成为返回值
sync
调用的值.因此在
and in your first example the second one is used: The closure can return a value, which then becomes the return
value of the sync
call. Therefore in
get {
return self.concurrentQueue.sync { return self._name }
}
sync { ... }
的返回值是self._name
并且返回
从吸气剂方法.这等效于(但比其简单)存储
临时变量中的值(这里的闭包返回Void
):
the return value of sync { ... }
is self._name
and that is returned
from the getter method. This is equivalent to (but simpler than) storing the
value in a temporary variable (and here the closure returns Void
):
get {
var result: String!
self.concurrentQueue.sync { result = self._name }
return result
}
当然,仅适用于同步调度的闭包,
不适用于异步调用.这些被存储以供以后执行,并且必须
返回Void
:
Of course that works only with synchronously dispatched closures,
not with asynchronous calls. These are stored for later execution and must
return Void
:
public func async(..., execute work: @escaping @convention(block) () -> Swift.Void)
这篇关于在Swift中创建线程安全读取时,为什么在并发队列之外创建变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!