I had the need for a concurrent map recently. I had a part of a program which
needed to read chunks of data and concurrently process them and assemble the
results in an array. This isn’t necessarily as obvious as it sounds, because of
arrays being value types. I came up with the following snippet which I’d like
to check for correctness; it could also be helpful to others.
Perhaps this is something Dispatch should provide out-of-the-box?
- Karl
extension DispatchQueue {
static func concurrentMap<T>(iterations: Int, execute block: (Int) -> T) ->
[T] {
var result = Array<T>()
result.reserveCapacity(iterations)
result.withUnsafeMutableBufferPointer { (results: inout
UnsafeMutableBufferPointer<T>) in
concurrentPerform(iterations: iterations) { idx in
results[idx] = block(idx)
}
}
return result
}
}
extension Array {
func concurrentMap<T>(execute block: (Element)->T) -> [T] {
return DispatchQueue.concurrentMap(iterations: count) { block(self[$0]) }
}
}
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users