有很多方法,但我的主要建议是研究使用libdispatch.
而不是产生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
Run Code Online (Sandbox Code Playgroud)
另一种方法是使用信号量,posix或dispatch(http://www.csc.villanova.edu/~mdamian/threads/posixsem.html有一些信息,http://developer.apple.com/也是如此)library/ios /#documentation/General/Conceptual/ConcurrencyProgrammingGuide/OperationQueues/OperationQueues.html).
(编辑后再添加一个替代方案):
如果您的所有线程基本上都在完成相同的工作(即拆分任务而不是执行大量不同的任务),这也可以很好地工作,并且更简单:
dispatch_apply(count, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(size_t i){
doWork(someData, i);
});
Run Code Online (Sandbox Code Playgroud)