在 Objective-C(和 Swift)中弱属性是线程安全的吗?
In Objective-C (and Swift) are weak properties thread safe?
当它们因为最后一个强引用消失而被 nil'd 时,如果在另一个线程上发生这种情况,你会有问题吗?如果是这样,使用 atomic 是否正确?因为我相信 Swift 没有原子,所以那里的线程安全弱 属性 需要什么?
Swift 中几乎没有任何内容本质上是线程安全的 — 引用、弱引用、数组、字符串或任何其他可变值都不是。
如果你想write/read或write/write从两个线程访问任何东西,你必须使用锁来确保安全。
https://medium.com/@mohit.bhalla/thread-safety-in-ios-swift-7b75df1d2ba6
这个link应该有帮助!
weak
是 ARC 的一部分,并且 Clang 承诺按照您描述的方式成为原子。具体请参阅 Clang 的自动引用计数文档中的 4.2 Semantics 部分。
对此特别感兴趣的是这些部分(添加了重点):
阅读
For __weak objects, the current pointee is retained and then released at the end of the current full-expression. This must execute atomically with respect to assignments and to the final release of the pointee.
作业
For __weak objects, the lvalue is updated to point to the new pointee, unless the new pointee is an object currently undergoing deallocation, in which case the lvalue is updated to a null pointer. This must execute atomically with respect to other assignments to the object, to reads from the object, and to the final release of the new pointee.
请注意,许多其他操作不是原子操作,尤其是强分配(例如,在两个不同的线程上分配强 属性)。但是保留计数本身是线程安全的,这正是您在这里担心的部分。您可以在任何线程上自由保留和释放对象,最后的保留计数将是正确的,包括 "implicit" 由于 weak
分配而释放。这都是以下内容的直接结果:
objc_retain
定义为 "exactly as if the object had been sent the retain
message."
- "Object allocation and retain count functions" 是 explicitly thread-safe.
所有这一切的结果是,与 Cocoa 的大部分内容不同,引用计数几乎总是跨线程安全处理。
当它们因为最后一个强引用消失而被 nil'd 时,如果在另一个线程上发生这种情况,你会有问题吗?如果是这样,使用 atomic 是否正确?因为我相信 Swift 没有原子,所以那里的线程安全弱 属性 需要什么?
Swift 中几乎没有任何内容本质上是线程安全的 — 引用、弱引用、数组、字符串或任何其他可变值都不是。
如果你想write/read或write/write从两个线程访问任何东西,你必须使用锁来确保安全。
https://medium.com/@mohit.bhalla/thread-safety-in-ios-swift-7b75df1d2ba6
这个link应该有帮助!
weak
是 ARC 的一部分,并且 Clang 承诺按照您描述的方式成为原子。具体请参阅 Clang 的自动引用计数文档中的 4.2 Semantics 部分。
对此特别感兴趣的是这些部分(添加了重点):
阅读
For __weak objects, the current pointee is retained and then released at the end of the current full-expression. This must execute atomically with respect to assignments and to the final release of the pointee.
作业
For __weak objects, the lvalue is updated to point to the new pointee, unless the new pointee is an object currently undergoing deallocation, in which case the lvalue is updated to a null pointer. This must execute atomically with respect to other assignments to the object, to reads from the object, and to the final release of the new pointee.
请注意,许多其他操作不是原子操作,尤其是强分配(例如,在两个不同的线程上分配强 属性)。但是保留计数本身是线程安全的,这正是您在这里担心的部分。您可以在任何线程上自由保留和释放对象,最后的保留计数将是正确的,包括 "implicit" 由于 weak
分配而释放。这都是以下内容的直接结果:
objc_retain
定义为 "exactly as if the object had been sent theretain
message."- "Object allocation and retain count functions" 是 explicitly thread-safe.
所有这一切的结果是,与 Cocoa 的大部分内容不同,引用计数几乎总是跨线程安全处理。