Actor重入性陷阱与安全模式
深入解析Swift Actor模型中方法重入的底层机制,通过反例演示意外状态共享,并给出防重入设计模式。 · 难度:入门 · +10XP
Actor重入性陷阱与安全模式
Actor保证串行执行,但允许重入(reentrancy):当Actor方法内部调用异步函数时,其他任务可能插入执行。这会导致看似隔离的状态被意外修改。本教程通过银行转账场景展示重入Bug,并介绍nonisolated标记、值类型深拷贝以及手动挂起队列等防护策略。
actor BankAccount {
var balance: Int = 100
func transfer(amount: Int, to other: BankAccount) async {
print("Start transfer \(amount)")
let current = balance
await Task.yield() // 模拟挂起点
balance = current - amount
await other.deposit(amount)
print("End transfer")
}
func deposit(_ amount: Int) {
balance += amount
}
}