Swift 5.5 引入了 actor 关键字,用于在并发环境中保护共享的可变状态。它是 Swift Concurrency 中最关键的线程安全工具之一。
actor 类似于 class,但它自动保证其内部的可变状态是线程安全的。它通过序列化访问来防止数据竞争(data race)。
测试结果:
image.png
extension ViewController{
func testActor() {
Task {
await testActorConcurrency()
}
Task {
await testActorConcurrency2()
}
Task {
await testActorConcurrency3()
}
}
func testActorConcurrency() async {
let counter = Counter()
let taskCount = 1000
await withTaskGroup(of: Void.self) { group in
for _ in 0..<taskCount {
group.addTask {
await counter.increment()
}
}
}
let final = await counter.getValue()
print("✅ 最终计数值应为 \(taskCount),实际为 \(final)")
}
func testActorConcurrency2() async {
let counter = Counter2()
let taskCount = 1000
await withTaskGroup(of: Void.self) { group in
for _ in 0..<taskCount {
group.addTask {
await counter.increment()
}
}
}
let final = await counter.getValue()
print("✅ 最终计数值应为 \(taskCount),实际为 \(final)")
}
func testActorConcurrency3() async {
let counter = TestClass.Counter()
let taskCount = 1000
await withTaskGroup(of: Void.self) { group in
for _ in 0..<taskCount {
group.addTask {
await counter.increment()
}
}
}
let final = await counter.getValue()
print("✅ 最终计数值应为 \(taskCount),实际为 \(final)")
}
}
class Counter2 {
private var value = 0
func increment() {
value += 1
}
func getValue() -> Int {
return value
}
}
actor Counter {
private var value = 0
func increment() {
value += 1
}
func getValue() -> Int {
return value
}
}
enum TestClass {
//传统做法
class Counter {
private var value = 0
//默认串行线程
private let queue = DispatchQueue(label: "counter")
func increment() {
//同步串行
queue.sync {
value += 1
}
}
func getValue() -> Int {
//同步串行
return queue.sync {
value
}
}
}
}