Sendable 与线程安全检查
将数据标记为 Sendable ,编写 @Sendable 闭包,并在值类型、参与者和 @unchecked Sendable 之间做出选择,实现线程安全共享。
Sendable 与线程安全检查 是 CoddyKit 上的免费 Swift Academy 课时。 这是第 3 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Swift Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Swift Academy 课程共包含 3 节课。
什么是 Sendable?
Sendable是 Swift 确保数据能够在并发任务或隔离对象之间安全传递的方式。
- 大多数结构体和枚举会自动符合 Sendable。
- 类默认不符合 Sendable。
- 使用隔离对象或@unchecked Sendable(少见,并且需要手动确保安全)。
值类型更简单
包含 Sendable 成员的结构体符合 Sendable;在任务之间传递它们是安全的。
// Value types with value-only stored properties are Sendable.
// They are safe to transfer across tasks.
struct Point: Sendable { let x: Int; let y: Int }
func shift(_ p: Point) -> Point { Point(x: p.x + 1, y: p.y + 1) }
// Use in parallel tasks
Task {
let p = Point(x: 1, y: 2)
async let a = shift(p)
async let b = shift(p)
let (p1, p2) = await (a, b)
print(p1, p2) // Point(x: 2, y: 3) Point(x: 2, y: 3)
}类:使用隔离对象
隔离对象通过串行化访问,让引用语义在任务之间保持安全。
// Reference types (class) are not Sendable by default.
// Prefer actors to guard mutable state.
actor SafeCounter {
private var value = 0
func inc() { value += 1 }
func read() -> Int { value }
}
let counter = SafeCounter()
Task {
async let t1 = counter.inc()
async let t2 = counter.inc()
_ = await (t1, t2)
print(await counter.read()) // 2
}
// (Alternative) A plain class would need locks + @unchecked Sendable; see later.@Sendable 闭包
当闭包可能在其他执行器上运行时,将其标记为@Sendable。避免捕获不可发送的可变状态。
// Some APIs require closures to be @Sendable so captured values are safe.
func doTwice(_ f: @Sendable () -> Int) -> Int { f() + f() }
let base = 10
// Capturing an immutable value (let) is fine for @Sendable closures.
let result = doTwice { base + 1 }
print(result) // 22
// Detached tasks also use @Sendable under the hood:
let t = Task.detached { () -> Int in
// Do not capture non-Sendable mutable state here.
return 5 * 5
}
Task { print(await t.value) }@unchecked Sendable(进阶)
@unchecked Sendable会跳过编译器检查。只有在使用严格的内部同步(锁或队列)时才应使用它,并且应将其作为最后手段。
import Foundation
// Only when you KNOW it is safe: wrap with a lock and mark @unchecked Sendable.
final class Box<T>: @unchecked Sendable {
private var value: T
private let lock = NSLock()
init(_ value: T) { self.value = value }
func read() -> T {
lock.lock(); defer { lock.unlock() }
return value
}
func write(_ newValue: T) {
lock.lock(); value = newValue; lock.unlock()
}
}
let shared = Box<Int>(0)
let a = Task.detached { shared.write(1) }
let b = Task.detached { shared.write(2) }
Task {
_ = await (a.value, b.value)
print(shared.read()) // 1 or 2 (last writer wins, but no data race)
}最佳实践
指南:
- 优先使用值类型(更适合 Sendable)。
- 对共享可变状态使用隔离对象。
- 编写@Sendable闭包;避免捕获不可发送的可变对象。
- 只有在进行严格同步时,才使用@unchecked Sendable。
Sendable 的含义
快速检查:Sendable 承诺了什么?
回顾
回顾:使用 Sendable 表示跨任务安全性,优先使用参与者类型或值类型,编写 @Sendable 闭包,并且仅在内部实现已得到良好同步时使用 @unchecked Sendable。
常见问题解答
「Sendable 与线程安全检查」课时是免费的吗?
是的 — 「Sendable 与线程安全检查」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Swift Academy 课程的其余内容,请升级到 CoddyKit PRO。 Swift Academy 课程共包含 3 节课。
「Sendable 与线程安全检查」这节课中我会学到什么?
将数据标记为 Sendable ,编写 @Sendable 闭包,并在值类型、参与者和 @unchecked Sendable 之间做出选择,实现线程安全共享。 你通过在浏览器中直接运行的动手代码来练习 Swift Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 Swift Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 Swift Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 3 节。
「Sendable 与线程安全检查」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 Swift Academy 课中编写并运行代码吗?
能。每节 Swift Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- 使用 TaskGroup 实现并行
- 参与者与数据隔离、nonisolated
- Sendable 与线程安全检查