Swift 组任务不并行运行

标签 swift async-await concurrency swift-concurrency

问题:

  • 为什么组任务没有并行运行?
  • 我错过了什么还是这是一个错误?

输出:

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?

您在 for-in 中有 await withTaskGroup,因此您的代码会在每次迭代时等待组任务完成。

你可能想做这样的事情吗?

    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
    }

关于Swift 组任务不并行运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68900341/

相关文章:

c# - WebForms 事件中的异步

c++ - 在析构函数(可能)被调用后使用对象引用

ios - 如何在 iOS 9 中使用 Swift 从 CMSampleBuffer 中提取像素数据进行处理?

ios - 如何在 iOS 应用程序中验证电子邮件地址?

ios - 在 UITextField 外部点击以停止编辑

java - EJB 方法的并发线程

java - 为什么要在 invokeAll 方法之后调用 join 呢?

ios - 快速通过 segue 传递数据时出现问题

node.js - 将异步等待查询包装在 try catch 中

c# - 寻找指导以了解如何使用Async和Await进行异步编程