Swift - 惰性 var 线程安全吗? [英] Swift - is lazy var thread-safe?

查看:15
本文介绍了Swift - 惰性 var 线程安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

也许这个问题需要一些上下文.

Maybe this question requires a bit of context.

我一直在使用 Core Data 处理我的持久层,发现 Core Data 不是线程安全的,因此需要 NSManagedObjectContext 仅限于每个线程.

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.

所以我的方法是创建自定义后台线程 NSManagedObjectContext 来执行获取、保存等操作,同时创建主线程 NSManagedObjectContext 将用于获取 从获取的 NSManagedObjectId 中获取 NSManagedObject 并将其传递给调用方方法.

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.

默认情况下,Xcode 使用 lazy var 为所有 NSManagedObjectContextNSManagedObjectModel 等生成与 Core Data 相关的模板代码.

By default, Xcode generates template code related to Core Data using lazy var for all NSManagedObjectContext, NSManagedObjectModel etc.

所以我的问题是要不要

使用 lazy var 实例化方法来创建 NSManagedObjectContext,前提是 lazy var 为每个尝试访问的线程(不是线程-安全吗?)

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?)

在每个线程中为NSManagedObjectContext声明单独的变量,并使所有线程相关的方法引用两个不同的NSManagedObjectContext,前提是lazy var是线程-safe(?) 并且无论线程​​如何访问都只创建一次.

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.

先谢谢你!

任何在核心数据并发问题上苦苦挣扎的人,这篇文章 列出了一个非常好的设计模式,正如 Aaron 在下面的评论中指出的那样!

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!

推荐答案

来自 TheSwift 编程语言:属性:

如果一个用 lazy 修饰符标记的属性被多个线程同时访问并且该属性尚未初始化,则不能保证该属性只会被初始化一次.

If a property marked with the lazy modifier is accessed by multiple threads simultaneously and the property has not yet been initialized, there is no guarantee that the property will be initialized only once.

lazy var 不是线程安全的.你可以使用

lazy var is not thread safe. You can use

  • dispatch_once(每个应用生命周期运行一次)
  • 一个常量(let)
  • 嵌套结构模式(通常用于单例)
  • dispatch_once (runs once per lifetime of the app)
  • a constant (let)
  • the nested struct pattern (typically used for singletons)

为了线程安全.(有关示例,请参阅此问题.)

for thread safety. (See this question for some examples.)

您也可以使用 NSRecursiveLock 使用自己的锁定,但这可能不如 dispatch_once 有效.

You could also employ your own locking using NSRecursiveLock but that's probably not as efficient as dispatch_once.

这篇关于Swift - 惰性 var 线程安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆