我想知道是否有人知道使用 Swift 在 iOS 中同时运行 x
个线程的直接方法。我正在尝试将照片分成多个部分并同时分析它们。我已经调查过了,有很多使用主线程和后台线程的讨论和示例,但我似乎找不到任何运行超过这 2 个线程的示例。例如在 Java 中我可以这样做:
public class ConcurrentAnalysis implements Runnable
{
private static volatile int counter = 0;
public void run()
{
// Increment count by 2
counter += 2;
}
public static void main(String args[])
{
Thread thread1 = new Thread();
Thread thread2 = new Thread();
thread1.start();
thread2.start();
try
{
thread1.join();
thread2.join();
}
catch (InterruptedException e){ System.out.println("Exception Thrown: " + e.getMessage()); }
}
}
我知道在这个例子中我只使用了 2 个线程,但我可以添加任意数量的线程。我真的只是想做一些类似于上述 Java 代码的事情,但是是在 Swift 中。
最佳答案
1。不要直接使用线程。有更好的解决方案:
有一个很棒的库可用于 GCD - Async
NSOperationQueue - 当您需要控制执行操作的顺序时非常有用。
2。不要在线程之间共享可变数据
如果你这样做,那么你需要一些同步机制,比如:锁、互斥锁。
使用这种架构真的很难。
3。使用不可变数据结构
不可变数据结构可以安全地在多线程中工作,因为没有人可以更改它们,因此您可以同时在多个线程中安全地处理(读取)数据。
structs
是不可变的值类型,是多线程的绝佳解决方案。
更好的解决方案
线程获取输入数据,处理并返回结果。
这样你就可以让你的线程不 protected ,他们可以同时按下同一个图像。
例子:
class Multithread {
func processImage(image: UIImage, result:(UIImage -> Void) ) {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0)) {
//Do what you want with image because UIImage is immutable
//Do work with image
var resultImage = image
let data = resultImage.CGImage
//pass result to the calling thread, main threa in our example
dispatch_async(dispatch_get_main_queue()) {
//assign new image
result(resultImage)
}
}
}
}
// Use example
if let image = UIImage(named: "image") {
let worker = Multithread()
//Run multiple workers.
worker.processImage(image) { resultImage in
//result
println(resultImage)
}
worker.processImage(image) { resultImage in
//result
println(resultImage)
}
worker.processImage(image) { resultImage in
//result
println(resultImage)
}
worker.processImage(image) { resultImage in
//result
println(resultImage)
}
}
如果您使用异步框架,processImage
会是这样的:
func processImage(image: UIImage, result:(UIImage -> Void) ) {
Async.background {
//Do what you want with image because UIImage is immutable
//Do work with image
var resultImage = image
let data = resultImage.CGImage
//pass result to the calling thread, main threa in our example
Async.main {
//assign new image
result(resultImage)
}
}
}
关于iOS - 在多个线程上处理照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29860957/