我明白,演员体内的所有并行工作不知何故都会变成连续剧,这是某种同步过程的一部分.我们可以看到,应该并行完成的async let个工作在Actor1中是按顺序完成的,这很可能是由于参与者的内部同步.但是,尽管AnActor内部同步,但withTaskGroup-工作并行运行,但为什么?)
编辑:同时,我想说,当使用await从参与者的内部外部调用时,我理解同步是如何工作的,但我不理解同步是如何在参与者内部工作的,以调用参与者内部的异步并行任务.
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView().task {
//await AnActor().performAsyncTasks() // uncomment this alternately and run
//await Actor1().performAsyncTasks() // uncomment this alternately and run
}
}
}
}
actor Actor1 {
func performAsyncTasks() async {
async let _ = asyncTasks1() // this not running in parallel
async let _ = asyncTasks2() // this not running in parallel
}
func asyncTasks1() async {
for i in 1...10_000_0 {
print("In Task 1: \(i)")
}
}
func asyncTasks2() async {
for i in 1...10_000_0 {
print("In Task 2: \(i)")
}
}
} // the printed text are in series with Task 1 and Task 2 in console
actor AnActor {
var value = 0
func performAsyncTasks() async {
value = await withTaskGroup(of: Int.self) { group in
group.addTask { // this running in parallel, why?!
var value1 = 0
for _ in 1...10_000 {
print("Task1")
value1 += 1
}
return value1
}
group.addTask { // this running in parallel, why?!
var value2 = 0
for _ in 1...10_000 {
value2 += 1
print("Task2")
}
return value2
}
return await group.reduce(0, +)
}
print(value)
}
} // the printed text are mixed with Task 1 and Task 2 in console