如何检查多个并发线程何时完成?

How to check when multiple concurrent threads have finished?

我有这样的代码:

myArray.forEach { item in
   concurentOperation(item)
}

数组中的每一项都经过一个并发操作函数,该函数在不同的线程中运行,我不确定到底是哪个线程或多少个线程,因为该函数来自第三方库并且不受我控制。我需要一种方法来找出所有操作完成后的结果。

我该怎么做?

不修改 concurentOperation() 这是不可用的,抱歉...

更新用户@Scriptable

下一个片段演示了为什么他的解决方案不起作用...

import PlaygroundSupport
import Dispatch

PlaygroundPage.current.needsIndefiniteExecution = true

let pq = DispatchQueue(label: "print", qos: .background)
func dprint(_ items: Any...) {
    pq.async {
        let r = items.map{ String(describing: [=10=]) }.joined(separator: " ")
        print(r)
    }
}

func concurrentOperation<T>(item: T) { // dummy items
    DispatchQueue.global().async {
        // long time operation
        for i in 0..<10000 {
            _ = sin(Double(i))
        }
        dprint(item, "done")
    }
}



let myArray = [1,2,3,4,5,6,7,8,9,0]
let g = DispatchGroup()
myArray.forEach { (item) in
    DispatchQueue.global().async(group: g) {
        concurrentOperation(item: item)
    }
}
g.notify(queue: DispatchQueue.main) {
    dprint("all jobs done???")
}

更新 2

不修改ConcurrentOperation()的代码

DispatchQueue.global().async(group: g) {
            concurrentOperation(item: item)
        }

因为concurrentOperation是异步函数,进入调度组后立即离开。如果它是同步的,那么这个问题就没有意义。