Below is a sample function where I try to run one main group, wait, then run two other background tasks on separate threads, wait, then return a value altered in the general blocks shown below. What is shown below is my guess at how to do this. It works if I run these blocks all in one block. It fails when I separate the blocks. Does anyone have an example of how they accomplish something similar? Thanks in advance for your help.
-(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;
}
There are lots of different ways to do this, but the most conceptually simple (or at least obvious) way would be to create a group for each stage of your “pipeline”, then have the completion callback for group A schedule the work on group B which also has a completion callback which schedules the work on group C.
The key here is not to actually “wait” for a group to complete – that’s unnecessary. Groups can have completion blocks that will get run automatically when the last block in that group finishes (see dispatch_group_notify()), and this is a good way of creating “fan in” points where you’ve fanned out a bunch of work in the group.