Skip to content

Instantly share code, notes, and snippets.

@alextrob
Last active January 13, 2021 12:24
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alextrob/a4e9885f063e1d5ea02e77771c464b78 to your computer and use it in GitHub Desktop.
Save alextrob/a4e9885f063e1d5ea02e77771c464b78 to your computer and use it in GitHub Desktop.
Multi-core for-each and map
public extension Array {
/// Synchronous
func concurrentMap<T>(transform: @escaping (Element) -> T) -> [T] {
let result = UnsafeMutablePointer<T>.allocate(capacity: count)
DispatchQueue.concurrentPerform(iterations: count) { i in
result.advanced(by: i).initialize(to: transform(self[i]))
}
let finalResult = Array<T>(UnsafeBufferPointer(start: result, count: count))
result.deallocate()
return finalResult
}
/// Synchronous
func concurrentForEach(action: @escaping (Element) -> Void) {
_ = concurrentMap { _ = action($0) }
}
}
// Works just like regular `map` and `forEach`.
// This is a simple example to show API usage; don't actually use this for such tiny amounts of work.
let things = [1, 2, 3, 4]
// 1
// 2
// 3
// 4
things.concurrentForEach {
print($0)
}
let multipliedByTwo = things.concurrentMap { $0 * 2 } // [2, 4, 6, 8]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment