我有很多 NSThreads,我想在它们工作的时候 sleep 。我该怎么做? iOS SDK 中是否有 WinApi 函数 WaitForSingleObject/WaitForMultipleObjects 的模拟?
最佳答案
有很多方法,但我的主要建议是考虑使用 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
另一种方法是使用信号量,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);
});
关于iphone - 等待 NSThread,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4845451/