我有很多NSThreads,我想在他们工作的时候睡觉。我该怎么做呢?iOS SDK中是否有类似的WinApi函数WaitForSingleObject/WaitForMultipleObjects?
发布于 2011-01-31 05:02:10
有相当多的方法,但我的主要建议是考虑使用库调度。
这样做,而不是生成NSThreads:
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
/* work to do in a thread goes here */
});
/* repeat for other threads */
dispatch_group_wait(group, DISPATCH_TIME_FOREVER); //wait for all the async tasks in the group to complete有关文档,请参阅http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dispatch_group_async.3.html。
另一种方法是使用信号量,可以是posix,也可以是分派(和http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html一样,http://www.csc.villanova.edu/~mdamian/threads/posixsem.html也有一些信息)。
(编辑后再添加一个备选方案):
如果你的所有线程都在做本质上相同的工作(例如,拆分任务而不是做一堆不同的任务),这也会很好地工作,而且要简单得多:
dispatch_apply(count, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t i){
doWork(someData, i);
});发布于 2011-01-31 07:08:31
这听起来真的像是你应该重新思考你的应用的架构。拥有多个线程,特别是在iOS上,与简单的设计相比,肯定会更慢,也更麻烦。
在iOS上,只有一个核心,总线带宽非常有限。
尽可能使用系统提供的更高级别的并发工具(NSOperation、调度和任何异步API)要好得多。
https://stackoverflow.com/questions/4845451
复制相似问题