2

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.

1
  • 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? Commented Aug 26, 2011 at 16:52

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

The practical solution is as you describe: beneath the API create a custom queue targeted at a concurrent queue (it works, I tried it). However that is not the question being asked. The question requires only using the available asynchronous API.
0

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

1 Comment

NSOperationQueue is high-level, but clumsy, the biggest obstacle being lack of variable value capture. GCD also allows me to redesign my APIs, getting rid of delegate relationships for example.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.