我有以下代码:-

extension Collection {

    // EZSE : A parralelized map for collections, operation is non blocking
    public func pmap<R>(_ each: (Self.Iterator.Element) -> R) -> [R?] {
        let indices = indicesArray()
        var res = [R?](repeating: nil, count: indices.count)

        DispatchQueue.concurrentPerform(iterations: indices.count) { (index) in
            let elementIndex = indices[index]
            res[index] = each(self[elementIndex])
        }

        // Above code is non blocking so partial exec on most runs
        return res
    }

    /// EZSE : Helper method to get an array of collection indices
    private func indicesArray() -> [Self.Index] {
        var indicesArray: [Self.Index] = []
        var nextIndex = startIndex
        while nextIndex != endIndex {
            indicesArray.append(nextIndex)
            nextIndex = index(after: nextIndex)
        }
        return indicesArray
    }
}

在此处的return语句res处,它通常以部分执行完成后返回。从某种意义上说,并发Perform是不阻塞的。我不确定如何继续等待。我应该使用调度组/期望之类的方法还是有一些更简单,更优雅的方法?本质上,我正在寻找一种快速的等待通知抽象。

最佳答案

您可以尝试如下操作:

// EZSE : A parralelized map for collections, operation is non blocking
public func pmap<R>(_ each: @escaping (Self.Iterator.Element) -> R) -> [R] {
    let totalCount = indices.count
    var res = ContiguousArray<R?>(repeating: nil, count: totalCount)

    let queue = OperationQueue()
    queue.maxConcurrentOperationCount = totalCount

    let lock = NSRecursiveLock()
    indices
        .enumerated()
        .forEach { index, elementIndex in
            queue.addOperation {
                let temp = each(self[elementIndex])
                lock.lock()
                res[index] = temp
                lock.unlock()
            }
    }
    queue.waitUntilAllOperationsAreFinished()

    return res.map({ $0! })
}

关于ios - 如何快速实现并行映射,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/42619447/

10-17 03:15