-
-
Save alextrob/a4e9885f063e1d5ea02e77771c464b78 to your computer and use it in GitHub Desktop.
Multi-core for-each and map
This file contains 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
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) } | |
} | |
} |
This file contains 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
// 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