Swift - 是懒惰var线程安全? [英] Swift - is lazy var thread-safe?
问题描述
也许这个问题需要一点上下文。
我一直在使用Core Data工作在持久层,发现Core Data不是线程级的,安全,因此需要 NSManagedObjectContext
只限于每一个线程。
所以我的方法是创建自定义背景线程 NSManagedObjectContext
,它执行获取,保存等,同时创建主线程 NSManagedObjectContext
NSManagedObjectId
并将其传递给调用方法。
默认情况下,Xcode会为所有 NSManagedObjectContext
,使用
等。 lazy var
NSManagedObjectModel
所以我的问题是是否
创建 NSManagedObjectContext
的c $ c> lazy var 实例化方法,前提是 lazy var
每个线程尝试访问的对象(不是线程安全?)
或
NSManagedObjectContext
在每个线程,并使所有线程相关的方法引用两个不同 NSManagedObjectContext
lazy var 是线程安全的(?),并且在访问时只创建一次,而不管线程。
p>
编辑:任何遇到Core Data并发问题的人,本文介绍了一个非常好的设计模式,如Aaron在下面的注释中所指出的!
lazy var
不是线程安全的。您可以使用 dispatch_once
,一个常量( let
)或嵌套结构模式(通常用于单例)安全。你也可以使用 NSRecursiveLock
使用自己的锁,但这可能不如 dispatch_once
有效。
Maybe this question requires a bit of context.
I've been working on my persistence layer using Core Data and found out that Core Data isn't thread-safe and thus requires NSManagedObjectContext
to be confined to each one thread only.
So my approach is to create custom background thread NSManagedObjectContext
which executes fetching, saving etc, while also to create main thread NSManagedObjectContext
which will be used to get NSManagedObject
from fetched NSManagedObjectId
and pass it to caller method.
By default, Xcode generates template code related to Core Data using lazy var
for all NSManagedObjectContext
, NSManagedObjectModel
etc.
So my question is whether to
use the lazy var
instantiation approach for creating NSManagedObjectContext
, provided that lazy var
initiates an object for each thread trying to access (not thread-safe?)
or
declare separate variables for NSManagedObjectContext
in each thread and make all thread-related methods to reference two different NSManagedObjectContext
provided that lazy var
is thread-safe(?) and created only once when it is accessed regardless of thread.
Thank you in advance!
edit: Anyone who is struggling with Core Data concurrency issue, this article lays out a very nice design pattern to work with as pointed out by Aaron in the comment below!
lazy var
is not thread safe. You can use dispatch_once
, a constant (let
), or the nested struct pattern (typically used for singletons) for thread safety. You could also employ your own locking using NSRecursiveLock
but that's probably not as efficient as dispatch_once
.
这篇关于Swift - 是懒惰var线程安全?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!