> On 30 Oct 2016, at 09:15, Karl <raziel.im+swift-us...@gmail.com> wrote:
> 
> 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

Ah one second, I was refactoring this and forgot to test it. Here’s the actual 
code:

extension DispatchQueue {

  static func concurrentMap<T>(iterations: Int, execute block: (Int) -> T) -> 
[T] {

    let __result = UnsafeMutableRawBufferPointer.allocate(count: iterations * 
MemoryLayout<T>.stride)
    defer { __result.deallocate() }
    let _result  = __result.baseAddress?.assumingMemoryBound(to: T.self)
    let result   = UnsafeMutableBufferPointer<T>(start: _result, count: 
iterations)
    concurrentPerform(iterations: iterations) { idx in
      result[idx] = block(idx)
    }
    return Array(result)
  }
}

extension Array {
  func concurrentMap<T>(execute block: (Element)->T) -> [T] {
    return DispatchQueue.concurrentMap(iterations: count) { block(self[$0]) }
  }
}


Unfortunately I don’t think there’s a way to get an array to take over a +1 
UnsafeMutableBufferPointer without copying.

- Karl
_______________________________________________
swift-users mailing list
swift-users@swift.org
https://lists.swift.org/mailman/listinfo/swift-users

Reply via email to