Juk*_*ela 4 parallel-processing swift
什么是最接近的Swift等效的以下C&OpenMP代码(假设这n是巨大的,f很简单):
#openmp parallel for
for (int i = 0; i < n; ++i) {
a[i] = f(b[i]);
}
Run Code Online (Sandbox Code Playgroud)
并行化一个for循环,dispatch_apply对于这样的例行任务来说似乎很多工作.有没有聪明的捷径?
如果您的代码有循环,并且每次通过循环完成的工作独立于其他迭代中完成的工作,您可以考虑使用 dispatch_apply 或 dispatch_apply_f 函数重新实现该循环代码。这些函数将循环的每次迭代分别提交给调度队列进行处理。当与并发队列结合使用时,此功能可让您同时执行循环的多次迭代。
在这里阅读:https : //developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW2
快速:https : //developer.apple.com/documentation/dispatch/dispatchqueue/2016088-concurrentperform
DispatchQueue.concurrentPerform(iterations: 1000) { (index) in
print("current: \(index)")
}
Run Code Online (Sandbox Code Playgroud)
它(来自iBook)似乎还没有针对并行性的特定于swift的API /语言功能.在这一点上,使用GCD似乎是最好的选择,性能方面.如果您正在寻找代码简洁,您可以使用标准的Objective-C习惯用于并发数组枚举:
var array : Int[] = [1,2,3,4]
array.bridgeToObjectiveC().enumerateObjectsWithOptions(NSEnumerationOptions.Concurrent, {(obj: AnyObject!, index: Int, outStop: CMutablePointer<ObjCBool>) -> Void in
// Do stuff
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2718 次 |
| 最近记录: |