下面是一个示例函数,我尝试在其中运行一个主组,等待,然后在单独的线程上运行另外两个后台任务,等待,然后返回在下面的一般块中更改的值。下面显示的是我对如何做到这一点的猜测。如果我把这些块都放到一个块里就行了。当我把这些块分开时,它就失效了。有人能举个例子说明他们是如何做到类似的吗?提前感谢您的帮助。
-(NSString *)sampleFunction:(NSString*)inputString
{
__block NSString *returnString;
dispatch_group_t mainGroup = dispatch_group_create();
dispatch_group_t otherGroup = dispatch_group_create();
void (^firstBlock)(void) = ^(void)
{
...
};
void (^secondBlock)(void) = ^(void)
{
...
};
void (^thirdBlock)(void) = ^(void)
{
...
};
dispatch_group_async(oneGroup, dispatch_get_global_queue(0, 0), firstBlock);
dispatch_group_wait(oneGroup, sizeof(int));
dispatch_group_async(otherGroup, dispatch_get_global_queue(0, 0), secondBlock);
dispatch_group_async(otherGroup, dispatch_get_global_queue(0, 0), thirdBlock);
dispatch_group_wait(otherGroup, sizeof(int));
dispatch_release(userGroup);
dispatch_release(otherGroup);
return returnString;
}
dispatch_semaphore在这里是您的朋友。: -)
/* Create your semaphore with 0 */
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
/* wait on the semaphore, causes your second & third queue to wait */
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
/* At the end of your first queue finishing, signal the semaphore waiting in
the 2nd queue to take over */
dispatch_semaphore_signal(sema);
如果您想要一个更简单的解决方案,只需使用dispatch_apply(它为您完成信号量的工作)而不是这些组,尽管不完全确定您使用这些组是为了什么。
有很多不同的方法可以做到这一点,但最概念上简单(或至少明显)的方法是为你的"管道"的每个阶段创建一个组,然后让组a的完成回调调度组B的工作,组B也有一个完成回调调度组c的工作。
这里的关键是不要真正"等待"一个组完成——那是不必要的。组可以有完成块,当该组中的最后一个块完成时,完成块将自动运行(参见dispatch_group_notify()),这是创建"扇入"点的好方法,您已经在组中分散了一堆工作。