swift操作,-Swift Actor 完全指南:使用场景、性能优化与线程安全 - │ │ Server 隔离域 │ │ Connection 隔离域│ │
前言
传统并发编程的痛点
// ❌ 经典的数据竞争问题
class UnsafeCounter {
var count = 0
func increment() {
count += 1 // 非原子操作:读取 → 加1 → 写入
}
}
let counter = UnsafeCounter()
DispatchQueue.concurrentPerform(iterations: 1000) {
_ in
counter.increment()
}
print(counter.count) // 结果不确定!可能是 987, 991, 1000...
// ❌ 传统解决方案:手动加锁
class LockedCounter {
private var count = 0
private let lock = NSLock()
func increment() {
lock.lock()
defer {
lock.unlock() }
count += 1
}
func getCount() ->Int {
lock.lock()
defer {
lock.unlock() }
return count
}
}
// 问题:
// 1. 容易忘记加锁
// 2. 可能死锁
// 3. 锁的粒度难以把握
// 4. 编译器无法帮助检查
Actor 的解决方案
// ✅ Actor:编译器保证的线程安全
actor SafeCounter {
var count = 0
func increment() {
count += 1 // 编译器保证同一时间只有一个任务执行
}
func getCount() ->Int {
count
}
}
let counter = SafeCounter()
await withTaskGroup(of: Void.self) {
group in
for _ in 0..<1000 {
group.addTask {
await counter.increment()
}
}
}
print(await counter.getCount()) // 始终是 1000 ✅
基础概念
Actor 的定义与结构
// Actor 是引用类型,类似于 class
actor BankAccount {
// 所有存储属性都是隔离的
let accountId: String // let 常量
private(set) var balance: Decimal // 可变属性
private var transactionHistory: [Transaction] = []
// 初始化器
init(accountId: String, initialBalance: Decimal) {
self.accountId = accountId
self.balance = initialBalance
}
// 实例方法默认是隔离的
func deposit(_ amount: Decimal) {
guard amount > 0 else {
return }
balance += amount
transactionHistory.append(
Transaction(type: .deposit, amount: amount)
)
}
func withdraw(_ amount: Decimal) throws {
guard amount > 0 else {
throw BankError.invalidAmount }
guard balance >= amount else {
throw BankError.insufficientFunds }
balance -= amount
transactionHistory.append(
Transaction(type: .withdrawal, amount: amount)
)
}
// 计算属性也是隔离的
var recentTransactions: [Transaction] {
Array(transactionHistory.suffix(10))
}
}
struct Transaction {
enum TransactionType {
case deposit, withdrawal }
let type: TransactionType
let amount: Decimal
let timestamp = Date()
}
enum BankError: Error {
case invalidAmount
case insufficientFunds
}
Actor vs Class 对比
┌─────────────────────────────────────────────────────────────────────┐
│ Actor vs Class │
├─────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────────────────┐ ┌─────────────────────────────┐ │
│ │ Class │ │ Actor │ │
│ ├─────────────────────────────┤ ├─────────────────────────────┤ │
│ │ │ │ │ │
│ │ • 引用类型 ✓ │ │ • 引用类型 ✓ │ │
│ │ • 可继承 ✓ │ │ • 不可继承 ✗ │ │
│ │ • 同步访问 │ │ • 异步访问(跨隔离域) │ │
│ │ • 无内置同步 │ │ • 自动串行化访问 │ │
│ │ • 可能数据竞争 │ │ • 编译器保证安全 │ │
│ │ • 需要手动加锁 │ │ • 无需手动同步 │ │
│ │ │ │ │ │
│ └─────────────────────────────┘ └─────────────────────────────┘ │
│ │
│ 共同点: │
│ • 都是引用类型 │
│ • 可以遵循协议 │
│ • 可以有计算属性、方法、下标 │
│ • 可以有 deinit │
│ │
└─────────────────────────────────────────────────────────────────────┘
Actor 的访问规则
actor DataStore {
var items: [String] = []
func addItem(_ item: String) {
items.append(item)
}
var count: Int {
items.count
}
}
// ========== 从外部访问 Actor ==========
func externalAccess() async {
let store = DataStore()
// ✅ 调用方法需要 await
await store.addItem("Hello")
// ✅ 访问属性需要 await
let count = await store.count
// ❌ 编译错误:不能同步访问
// store.items.append("World")
// let c = store.count
}
// ========== 从内部访问 Actor ==========
extension DataStore {
func internalAccess() {
// ✅ 内部方法可以同步访问所有成员
items.append("Internal")
print(count)
addItem("Also OK") // 无需 await
}
func callAnotherActor(_ other: DataStore) async {
// ❌ 访问其他 actor 实例需要 await
await other.addItem("Cross-actor")
// ✅ 访问自己不需要
self.addItem("Self access")
}
}
隔离机制
Actor 隔离(Actor Isolation)
actor ImageCache {
private var cache: [URL: UIImage] = [:]
// isolated 方法(默认)
func getImage(for url: URL) ->UIImage? {
cache[url]
}
func setImage(_ image: UIImage, for url: URL) {
cache[url] = image
}
// nonisolated 方法
nonisolated func cacheKey(for url: URL) ->String {
url.absoluteString.md5Hash
}
// nonisolated 计算属性
nonisolated var cacheDirectory: URL {
FileManager.default.temporaryDirectory
.appendingPathComponent("ImageCache")
}
}
// 使用
func useCache() async {
let cache = ImageCache()
// isolated 成员需要 await
await cache.setImage(image, for: url)
let cached = await cache.getImage(for: url)
// nonisolated 成员不需要 await
let key = cache.cacheKey(for: url)
let dir = cache.cacheDirectory
}
理解隔离域(Isolation Domain)
actor Server {
var connections: [Connection] = []
func handleConnection(_ conn: Connection) {
// ✅ 在 Server 的隔离域内
connections.append(conn)
}
}
actor Connection {
let id: UUID
var isActive: Bool = true
init(id: UUID) {
self.id = id
}
func process(on server: Server) async {
// 这里在 Connection 的隔离域
isActive = true
// 跨越到 Server 的隔离域,需要 await
await server.handleConnection(self)
// 回到 Connection 的隔离域
isActive = false
}
}
// 隔离域图示
/*
┌─────────────────────────────────────────────────────────────────┐
│ 并发执行环境 │
├─────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Server 隔离域 │ │ Connection 隔离域│ │
│ │ │ await │ │ │
│ │ connections ◄──┼─────────┼── process() │ │
│ │ handleConn() │ │ isActive │ │
│ │ │ │ │ │
│ └─────────────────┘ └─────────────────┘ │
│ │ │ │
│ │ await │ │
│ └───────────────────────────┘ │
│ │
│ 同一时刻,每个隔离域内只有一个任务在执行 │
│ │
└─────────────────────────────────────────────────────────────────┘
*/
Sendable 与 Actor 边界
// Sendable:可以安全跨并发域传递的类型
// ✅ 值类型自动满足 Sendable(如果所有成员都是 Sendable)
struct Point: Sendable {
var x: Double
var y: Double
}
// ✅ 不可变类可以是 Sendable
final class ImmutableConfig: Sendable {
let apiKey: String
let timeout: TimeInterval
init(apiKey: String, timeout: TimeInterval) {
self.apiKey = apiKey
self.timeout = timeout
}
}
// ✅ Actor 自动满足 Sendable
actor DataManager: Sendable {
var data: [String] = []
}
// ⚠️ 使用 @unchecked Sendable 需要自行保证安全
final class ThreadSafeCache: @unchecked Sendable {
private let lock = NSLock()
private var storage: [String: Any] = [:]
func get(_ key: String) ->Any? {
lock.lock()
defer {
lock.unlock() }
return storage[key]
}
func set(_ key: String, value: Any) {
lock.lock()
defer {
lock.unlock() }
storage[key] = value
}
}
// Actor 边界的 Sendable 要求
actor Processor {
func process(_ data: Point) {
// ✅ Point 是 Sendable
// ...
}
// ❌ 编译错误:NSMutableArray 不是 Sendable
// func process(_ array: NSMutableArray) { }
// 返回值也需要是 Sendable
func getResult() ->Point {
// ✅
Point(x: 0, y: 0)
}
}
isolated 参数
// 使用 isolated 参数借用 actor 的隔离域
actor Account {
var balance: Decimal = 0
func deposit(_ amount: Decimal) {
balance += amount
}
}
// 普通函数,接收 isolated actor 参数
func transfer(
amount: Decimal,
from source: isolated Account, // 借用 source 的隔离域
to destination: Account // 普通参数
) async {
// 可以同步访问 source(因为 isolated)
guard source.balance >= amount else {
return }
source.balance -= amount
// 需要 await 访问 destination
await destination.deposit(amount)
}
// 使用
func performTransfer() async {
let accountA = Account()
let accountB = Account()
// 调用时需要 await(因为需要进入 accountA 的隔离域)
await transfer(amount: 100, from: accountA, to: accountB)
}
// 另一个例子:协议方法中的 isolated Self
protocol Resettable: Actor {
func reset() async
}
extension Resettable {
// isolated Self 让我们可以同步访问 self
func resetAndLog(isolated actor: Self) {
print("Resetting \(self)")
// 这里可以访问 actor 的隔离成员
}
}
MainActor
MainActor 基础
// MainActor 是一个全局 Actor,绑定到主线程
@MainActor
class ViewModel: ObservableObject {
@Published var items: [Item] = []
@Published var isLoading = false
@Published var errorMessage: String?
func loadItems() async {
isLoading = true
defer {
isLoading = false }
do {
// 网络请求在后台执行
let fetchedItems = try await api.fetchItems()
// 回到 MainActor 更新 UI 状态
items = fetchedItems
} catch {
errorMessage = error.localizedDescription
}
}
}
// SwiftUI 视图
struct ItemListView: View {
@StateObject private var viewModel = ViewModel()
var body: some View {
List(viewModel.items) {
item in
ItemRow(item: item)
}
.overlay {
if viewModel.isLoading {
ProgressView()
}
}
.task {
await viewModel.loadItems()
}
} 拼多多帮助力入口
}
MainActor 的使用方式
// 方式1:标记整个类型
@MainActor
class UIController {
var state: AppState = .idle
func updateState(_ newState: AppState) {
state = newState
}
}
// 方式2:标记单个方法
class DataProcessor {
func processData() async ->ProcessedData {
// 后台处理
let result = await heavyProcessing()
// 更新 UI 需要切换到 MainActor
await updateUI(with: result)
return result
}
@MainActor
func updateUI(with data: ProcessedData) {
// 安全更新 UI
}
}
// 方式3:标记属性
class MixedClass {
@MainActor var uiState: String = ""
var backgroundData: Data?
func process() async {
backgroundData = await fetchData()
// 更新 UI 属性需要切换
await MainActor.run {
uiState = "Updated"
}
}
}
// 方式4:MainActor.run
func updateFromBackground() async {
let data = await fetchData()
await MainActor.run {
// 这里在主线程执行
label.text = data.description
view.setNeedsLayout()
}
}
// 方式5:Task with MainActor
func handleButtonTap() {
Task {
@MainActor in
// 继承 MainActor
await performAction()
updateUI()
}
}
MainActor 与 UIKit/AppKit
// UIViewController 默认不是 @MainActor
// 需要显式标记或使用 MainActor.run
class MyViewController: UIViewController {
private var dataTask: Task?
override func viewDidLoad() {
super.viewDidLoad()
loadData()
}
private func loadData() {
dataTask = Task {
let data = await fetchData()
// ⚠️ 需要确保在主线程更新 UI
await MainActor.run {
self.updateUI(with: data)
}
}
}
@MainActor
private func updateUI(with data: Data) {
// 安全
tableView.reloadData()
}
deinit {
dataTask?.cancel()
}
}
// 更安全的方式:整个控制器标记为 @MainActor
@MainActor
class SafeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
Task {
let data = await fetchData()
updateUI(with: data) // 自动在主线程
}
}
private func updateUI(with data: Data) {
tableView.reloadData()
}
}
MainActor 与 nonisolated
@MainActor
class ViewModel: ObservableObject {
@Published var results: [SearchResult] = []
// 默认在 MainActor 上
func search(_ query: String) async {
let results = await performSearch(query)
self.results = results
}
// nonisolated:不在 MainActor 上执行
// 适合 CPU 密集型操作
nonisolated func performSearch(_ query: String) async ->[SearchResult] {
// 这里在后台线程执行
let data = await api.search(query)
return parseResults(data) // CPU 密集型解析
}
nonisolated private func parseResults(_ data: Data) ->[SearchResult] {
// 解析逻辑,不阻塞主线程
[]
}
// nonisolated 属性
nonisolated var searchHistoryPath: URL