简体   繁体   中英

How to check when multiple concurrent threads have finished?

I have code that goes like this:

myArray.forEach { item in
   concurentOperation(item)
}

Every item in the array goes through a concurrent operation function, which runs in different threads, I'm not sure exactly which thread or how many threads because the function is from a third party library and out of my control. I need a way to find out once all operations are finished.

How can I do this?

without modifying concurentOperation() this is NOT available, sorry ...

UPDATE for user @Scriptable

next snippet demonstrates, why his solution doesn't work ...

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: $0) }.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???")
}

UPDATE 2

without modifying the code of ConcurrentOperation()

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

the dispatch group is entered and immediately left because concurrentOperation is the asynchronous function. If it is synchronous then the question has no sense.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM