Parallel for loop in Swift

parallel-processing, swift

Solution

If your code has loops, and the work being done each time through the loop is independent of the work being done in the other iterations, you might consider reimplementing that loop code using the dispatch_apply or dispatch_apply_f function. These functions submit each iteration of a loop separately to a dispatch queue for processing. When used in conjunction with a concurrent queue, this feature lets you perform multiple iterations of the loop concurrently.

Read here: https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW2

For swift: https://developer.apple.com/documentation/dispatch/dispatchqueue/2016088-concurrentperform

DispatchQueue.concurrentPerform(iterations: 1000) { (index) in
     print("current: \(index)")
}

Problem

What is the closest Swift equivalent of the following C & OpenMP code (assume that `n` is huge and `f` is simple): ``` #openmp parallel for for (int i = 0; i < n; ++i) { a[i] = f(b[i]); } ``` Parallelising a for loop with striding and `dispatch_apply` seems like a lot of work for such a routine task. Is there any clever shortcut?

Original source