1

I have a complex sync job that does several asyncronous calls for content over HTTP. Each time this content is received, it asks for the next bit and so on. These are all daisey-chained in a big over-all sync job with data on the server.

There are probably 12 steps in this job chain. It seems to get stuck after around the 5th async request, the request never comes back and it hangs for ever waiting for it. I think it may have to do with too many threads being spawned because if I fire off the one it hangs at at the beginning it returns fine.

In the way I imagine it in my head, the main thread asks for async content a. When it comes back in its own asynchronous time it spawns a new thread which then asks for aync content b. When it comes back in its own sweet time it spawns a new thread which then asks for content c. Isn't a new thread being created everytime an async request returns a result?

Am I daisy-chaining these requests right? I was quite good at threads in Java development but I'm a bit confused on how they work in Obj-C. Do I need to use a Thread pool of say 3 threads and reuse these?

Sorry for the high-level question but I'm sure some experts can help clear the cloud of mystery around this.

Mike S
  • 4,092
  • 5
  • 35
  • 68
  • I think you would be better of using a NSOperationQueue. Just add your operation to that queue, it will handle them in order. This should keep the number of thread down. – rckoenes Apr 12 '11 at 11:34
  • Hmm ok. So when it comes back with a result asynchronously.. I 'launch' the next job by adding it to the queue and it will get fired automagically? – Mike S Apr 12 '11 at 11:52
  • It will get the operation from the queue as soon as the operation id finished. You can find a nice tutorial here: http://www.cimgf.com/2008/02/16/cocoa-tutorial-nsoperation-and-nsoperationqueue/ – rckoenes Apr 12 '11 at 11:55
  • Is a new thread spawned when an async request comes back? – Mike S Apr 12 '11 at 13:21
  • If you are doing one request per thread, that is about the least efficient model possible in any language..... – bbum Apr 12 '11 at 15:54

1 Answers1

2

NSOperationQueues are built on top of Grand Central Dispatch. If you need precise control over order of operations and the ability to dispatch synchronous requests you might want to use GCD directly. Using either, you don't really need to worry about thread creation/management. You simply queue your operations as needed by your app.

The Apple docs are fine on this IMHO but you can find a number of tutorials out there.

[EDIT: added link to Apple docs]

http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html

XJones
  • 21,959
  • 10
  • 67
  • 82