繁体   English   中英

大中央调度。 如何运行一个异步组,等待,然后运行另一个,再次等待,然后完成?

[英]Grand Central Dispatch. How to run one async group, wait, then run another, wait again, then finish?

下面是一个示例函数,我尝试运行一个主组,等待,然后在单独的线程上运行其他两个后台任务,等待,然后返回在下面所示的常规块中更改的值。 下面显示的是我对如何执行此操作的猜测。 如果我在一个程序段中全部运行这些程序段,它将起作用。 当我分离块时,它失败了。 有谁能举例说明他们如何完成类似的工作? 在此先感谢您的帮助。

-(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还有一个完成回调,该回调计划在C组上安排工作。

这里的关键不是要实际上“等待”一个小组完成-这是不必要的。 组中可以有完成块,当该组中的最后一个块结束时,它们将自动运行(请参阅dispatch_group_notify()),这是在“扇入”点创建扇形散布的好方法。组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM