等待NSThread

Sia*_*sou 0 iphone winapi ipad ios

我有很多NSThreads,我想在他们工作的时候睡觉.我该怎么做?在iOS SDK中是否存在WinApi函数WaitForSingleObject/WaitForMultipleObjects的模拟?

Cat*_*Man 6

有很多方法,但我的主要建议是研究使用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)

有关文档,请参阅http://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man3/dispatch_group_async.3.html.

另一种方法是使用信号量,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)