我的 iPhone 应用程序中有一个非常重复的方法(按顺序一遍又一遍地调用)。该方法非常庞大,大约需要一秒钟才能完成。
我的问题是:如果我要多线程运行它,比如同时在不同线程上调用 5 个方法,这会比一个接一个地运行 5 个调用快吗?我知道对于具有多核处理器的台式机,这将是一个优势,但我不确定 iPhone。
有什么建议吗?
最佳答案
使用 Grand Central Dispatch(又名 GCD 和 libdispatch),它只会做正确的事 (tm)。
如果您在全局队列之一上调用 dispatch_async,GCD 将根据系统工作负载计算是生成新线程来处理您提交的操作,还是在一个线程上连续运行它们。
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
// Do your calculations here
// If you want to run code on the main loop with the result of the calculations,
// do something like this
dispatch_async(dispatch_get_main_queue(), ^{
// Code to run on the main thread here
});
});
您还可以使用分派(dispatch)组在所有五个调用完成后运行一些代码。
看看 Concurrency Programming Guide和 GCD reference manual了解详情。
更新
另请参阅 this article from Ars在 GCD 上。他们解释了 GCD 如何决定如何调度 block 的一些细节。
关于iphone - 将一个操作分解为多个线程在 iPhone 上有优势吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3953721/