Thursday, April 15, 2021 [Tweets] [Favorites]

Collecting concurrentPerform(iterations:) Results in a Swift Array

David Smith:

Useful pattern for aggregating the results of parallel work in Swift:

let result = Array(unsafeUninitializedCapacity: count) { (buffer) in
  DispatchQueue.concurrentPerform(iterations: count) { (idx) in
    buffer[idx] = processItem(idx)
  }
}

Avoids making an extra buffer copy

If you make the Array up front and try to operate directly on it instead of the UnsafeMutableBufferPointer in that initializer, each thread will get its own copy due to copy-on-write, which generally is not what you wanted.

David Smith:

I would not trust it [with small array elements]. Aligned word-sized non-float things are your friends when dealing with concurrency. If you’re not sure, try TSAN, and consider just using a lock.

Previously:

Comments

Stay up-to-date by subscribing to the Comments RSS Feed for this post.

Leave a Comment