Skip to content

Instantly share code, notes, and snippets.

@RoshanNindrai
Last active August 5, 2019 15:34
Show Gist options
  • Select an option

  • Save RoshanNindrai/71901bb2648608ec621644a9cd439721 to your computer and use it in GitHub Desktop.

Select an option

Save RoshanNindrai/71901bb2648608ec621644a9cd439721 to your computer and use it in GitHub Desktop.
Parallel Map, Filter Implementation
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 }
}
}
@amomchilov

Copy link
Copy Markdown

You have an unsynchronized accesses to result, which critically breaks this code.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment