Swift 非 运行 并行分组任务
Swift Group Tasks not running in parallel
问题:
- 为什么小组任务没有运行并行?
- 我是不是遗漏了什么或者这是一个错误?
输出:
started 24
finished 24
--- 24
started 12
finished 12
--- 12
started 16
finished 16
--- 16
started 4
finished 4
--- 4
started 10
finished 10
--- 10
started 20
finished 20
--- 20
started 19
finished 19
--- 19
环境:
- macOS 11.5.2 (20G95)
- Xcode 版本 13.0 beta 5 (13A5212g)
- SwiftUI 项目
代码:
func groupTask() async -> [Int : Int] {
let ids = [24, 12, 16, 4, 10, 20, 19]
var prices = [Int : Int]()
for id in ids {
await withTaskGroup(of: (Int, Int).self) { group in
group.addTask(priority: .background) {
let price = await computePrice(for: id)
return (id, price)
}
for await (id, price) in group {
prices[id] = price
print("--- \(id)")
}
}
}
return prices
}
func computePrice(for id: Int) async -> Int {
print("started \(id)")
let duration = UInt64(id * 100_000_000)
await Task.sleep(duration)
print("finished \(id)")
return id * 2
}
Why are the group tasks not running in parallel?
你有 await withTaskGroup
inside for-in,所以你的代码在每次迭代时等待组任务完成。
您可能想做这样的事情?
func groupTask() async -> [Int : Int] {
let ids = [24, 12, 16, 4, 10, 20, 19]
var prices = [Int : Int]()
await withTaskGroup(of: (Int, Int).self) { group in
for id in ids {
group.addTask(priority: .background) {
let price = await computePrice(for: id)
return (id, price)
}
}
for await (id, price) in group {
prices[id] = price
print("--- \(id)")
}
}
return prices
}
问题:
- 为什么小组任务没有运行并行?
- 我是不是遗漏了什么或者这是一个错误?
输出:
started 24
finished 24
--- 24
started 12
finished 12
--- 12
started 16
finished 16
--- 16
started 4
finished 4
--- 4
started 10
finished 10
--- 10
started 20
finished 20
--- 20
started 19
finished 19
--- 19
环境:
- macOS 11.5.2 (20G95)
- Xcode 版本 13.0 beta 5 (13A5212g)
- SwiftUI 项目
代码:
func groupTask() async -> [Int : Int] {
let ids = [24, 12, 16, 4, 10, 20, 19]
var prices = [Int : Int]()
for id in ids {
await withTaskGroup(of: (Int, Int).self) { group in
group.addTask(priority: .background) {
let price = await computePrice(for: id)
return (id, price)
}
for await (id, price) in group {
prices[id] = price
print("--- \(id)")
}
}
}
return prices
}
func computePrice(for id: Int) async -> Int {
print("started \(id)")
let duration = UInt64(id * 100_000_000)
await Task.sleep(duration)
print("finished \(id)")
return id * 2
}
Why are the group tasks not running in parallel?
你有 await withTaskGroup
inside for-in,所以你的代码在每次迭代时等待组任务完成。
您可能想做这样的事情?
func groupTask() async -> [Int : Int] {
let ids = [24, 12, 16, 4, 10, 20, 19]
var prices = [Int : Int]()
await withTaskGroup(of: (Int, Int).self) { group in
for id in ids {
group.addTask(priority: .background) {
let price = await computePrice(for: id)
return (id, price)
}
}
for await (id, price) in group {
prices[id] = price
print("--- \(id)")
}
}
return prices
}