Understanding actor initialization 了解 actor 初始化

Understanding actor initialization 了解 actor 初始化

温馨提示:本文最后更新于2025-02-08 17:35:13,某些文章具有时效性,若有错误或已失效,请在下方留言

Swift’s actors run on their own executor most of the time, so they manage how and where their work is done. However, during the actor’s initialization its executor isn’t ready to take on work. So, the Swift team are working on a rule to keep everything safe: they want to make actors with an async initializer automatically move to the actor’s executor when its properties are all initialized.
Swift 的 actor 大部分时间都在自己的 executor 上运行,因此他们管理着工作完成的方式和位置。但是,在 actor 初始化期间,其执行程序尚未准备好执行工作。因此,Swift 团队正在制定一条规则来确保一切安全:他们希望让具有异步初始化器的 actor 在其属性全部初始化时自动移动到 actor 的执行程序。

Here’s how that looks in code:
下面是它在代码中的样子:

actor Actor {
    var name: String

    init(name: String) async {
        print(name)
        self.name = name
        print(name)
    }
}

let actor = await Actor(name: "Meryl")
下载图标
understanding-actor-initialization-1.zip
zip文件
49.8K

At the time of writing this feature isn’t fully implemented, but it’s the team’s goal to have this feature working in the future. So you should be aware that in code like the above the two print() calls might execute on entirely different threads – in effect, there’s an implicit actor hop as soon as self.name is assigned.
在撰写本文时,此功能尚未完全实现,但团队的目标是让此功能在将来发挥作用。因此,您应该知道,在上述代码中,两个 print() 调用可能在完全不同的线程上执行 – 实际上,一旦分配了 self.name,就会出现一个隐式的 actor 跃点。

© 版权声明
THE END
喜欢就支持一下吧
点赞0 分享