2
votes

I am using GCD on iOS to perform a a time-consuming task on a background thread. The API has a start method that takes two blocks as arguments, both called on the main queue. The first is called when the task starts and the second when the task finishes. This all works.

I actually need to do several of these time-consuming tasks. The API lets me start them all at the same time and then wait for each to finish and update the UI via the blocks. They run concurrently.

However what I actually I want to do is to sequence the time-consuming tasks (still starting each using the API described) so that I can start them all at the same time, have the first one run and give me its call-backs, then have the second one run and give me its call-backs, etc. until all are done.

What is the best way to achieve this with GCD and blocks?

If the tasks were synchronous, I'd just have a loop that ran each in turn, and run all of that asynchronously. But I have call-backs, so that will not work. I'd prefer not to have to chain them, since the object that makes all of this happen could disappear once it has started the sequence of events.

2
To clarify: adding a serial queue the other side of the API solves this. The key question is how to achieve the same thing with the current API and its async, concurrent behavior?Steve Weller

2 Answers

1
votes

You can create your own serial queue that will execute in FIFO order with dispatch_queue_create. You DO NOT need to specify that it is a serial queue. It will act this way by default.

Sample queue creation:

dispatch_queue_t my_q = dispatch_queue_create("Serial",NULL);

You own this queue, so failing to release it (with dispatch_release) will leak it.

More info is in Apple's docs here.

0
votes

Is there a particular reason you have to use GCD? Sounds like NSOperationQueue with concurrency of 1 is exactly what you want.