Collecting concurrentPerform(iterations:) Results in a Swift Array
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 theUnsafeMutableBufferPointer
in that initializer, each thread will get its own copy due to copy-on-write, which generally is not what you wanted.
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:
- High Performance Numeric Programming With Swift
- Underused and Overused GCD Patterns
- Swift 5 Exclusivity Enforcement