可以从异步函数安全地访问属性吗?

huangapple go评论52阅读模式
英文:

Can a property be safely accessed from async functions?

问题

使用Swift 5.5的async/await,我们可以从两个不同的异步函数中访问相同的属性吗?

例如,假设您有以下代码:

var foobarInstance: FooBar?

func start() async {
   foobarInstance = await buildFooBar()
   ....
}

func process() async {
   if let foo = self.foobarInstance {
      // 进行一些操作
   }
}

这种方式访问self.foobarInstance是安全的吗?Swift是否会自动处理这个问题?

英文:

With Swift's 5.5 async/await, can we access the same property from two different async functions?

For example, let's say you have:

var foobarInstance: FooBar?

func start() async {
   foobarInstance = await buildFooBar()
   ....
}

func process() async {
   if let foo = self.foobarInstance {
      // do something
   }
}

Is it safe to access self.foobarInstance that way? Does Swift handle that automatically?

答案1

得分: 3

async 函数本身是不足够的。但如果属性和方法都是 actor 隔离的,那么是的,你可以从多个方法中访问相同的属性。例如:

actor Qux {
    private var foobar: FooBar?
    
    func start() async {
        foobar = await buildFooBar()
        
    }
    
    func process() async {
        if let foobar {
            // 使用 `foobar` 做一些事情
        }
    }
}

在这种情况下,我使用了显式的 actor 类型,但它也适用于全局 actor(如 @MainActor)。

我不知道你的 FooBar 类型是什么,但如果你在 actor 隔离上下文之外暴露它,你可能需要确保它也是线程安全的(例如,Sendable)。在这种情况下,我明确将它设置为 private,以确保它不会不必要地暴露在此上下文之外。

请参考 WWDC 2021 视频 使用 Swift actor 保护可变状态 和 2022 视频 使用 Swift Concurrency 消除数据竞争

英文:

The async functions alone are not sufficient. But if both the property and the methods are actor-isolated, then, yes, you can access the same property from multiple methods. E.g.:

actor Qux {
    private var foobar: FooBar?
    
    func start() async {
        foobar = await buildFooBar()
        
    }
    
    func process() async {
        if let foobar {
            // do something with `foobar`
        }
    }
}

In this case, I am using an explicit actor type, but it also works with global actors (such as @MainActor).

I do not know what your FooBar type is, but if you ever expose it outside this actor-isolated context, you may want to make sure that it is thread-safe, too (e.g., Sendable). In this case, I explicitly made it private to ensure it was not unnecessarily exposed outside of this context.

See WWDC 2021 video Protect mutable state with Swift actors and 2022 video Eliminate data races using Swift Concurrency.

huangapple
  • 本文由 发表于 2023年2月24日 04:16:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/75549901.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定