Last active
August 5, 2019 15:34
-
-
Save RoshanNindrai/71901bb2648608ec621644a9cd439721 to your computer and use it in GitHub Desktop.
Parallel Map, Filter Implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import Foundation | |
| public extension Array { | |
| func pmap<T>(transformer: @escaping (Element) -> T) -> [T] { | |
| var result: [Int: [T]] = [:] | |
| guard !self.isEmpty else { | |
| return [] | |
| } | |
| let coreCount = ProcessInfo.processInfo.activeProcessorCount | |
| let sampleSize = Int(ceil(Double(count) / Double(coreCount))) | |
| let group = DispatchGroup() | |
| for index in 0..<sampleSize { | |
| let startIndex = index * coreCount | |
| let endIndex = Swift.min((startIndex + (coreCount - 1)), count - 1) | |
| result[startIndex] = [] | |
| group.enter() | |
| DispatchQueue.global().async { | |
| for index in startIndex...endIndex { | |
| result[startIndex]?.append(transformer(self[index])) | |
| } | |
| group.leave() | |
| } | |
| } | |
| group.wait() | |
| return result.sorted(by: { $0.0 < $1.0 }).flatMap { $0.1 } | |
| } | |
| func pfilter(filter: @escaping (Element) -> Bool) -> [Element] { | |
| var result: [Int: [Element]] = [:] | |
| guard !self.isEmpty else { | |
| return [] | |
| } | |
| let coreCount = ProcessInfo.processInfo.activeProcessorCount | |
| let sampleSize = Int(ceil(Double(count) / Double(coreCount))) | |
| let group = DispatchGroup() | |
| for index in 0..<sampleSize { | |
| let startIndex = index * coreCount | |
| let endIndex = Swift.min((startIndex + (coreCount - 1)), count - 1) | |
| result[startIndex] = [] | |
| group.enter() | |
| DispatchQueue.global().async { | |
| for index in startIndex...endIndex where filter(self[index]) { | |
| result[startIndex]?.append(self[index]) | |
| } | |
| group.leave() | |
| } | |
| } | |
| group.wait() | |
| return result.sorted(by: { $0.0 < $1.0 }).flatMap { $0.1 } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You have an unsynchronized accesses to
result, which critically breaks this code.