When using GCD, we want to wait until two async blocks are executed and done before moving on to the next steps of execution. What is the best way to do that?
We tried the following, but it doesn't seem to work:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
// block1
});
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
// block2
});
// wait until both the block1 and block2 are done before start block3
// how to do that?
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^ {
// block3
});
Not to say other answers are not great for certain circumstances, but this is one snippet I always user from Google:
Another GCD alternative is a barrier:
Just create a concurrent queue, dispatch your two blocks, and then dispatch the final block with barrier, which will make it wait for the other two to finish.
Expanding on Jörn Eyrich answer (upvote his answer if you upvote this one), if you do not have control over the
dispatch_async
calls for your blocks, as might be the case for async completion blocks, you can use the GCD groups usingdispatch_group_enter
anddispatch_group_leave
directly.In this example, we're pretending
computeInBackground
is something we cannot change (imagine it is a delegate callback, NSURLConnection completionHandler, or whatever), and thus we don't have access to the dispatch calls.In this example, computeInBackground:completion: is implemented as:
Output (with timestamps from a run):
Accepted answer in swift: