Skip to content

Instantly share code, notes, and snippets.

@alextrob
Last active January 13, 2021 12:24
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Embed
What would you like to do?
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