Asynchronous Design Patterns with Blocks GCD

I'm a newbie . Is there an example code base I can look at that shows how to


1 ) fire up JSON queries/reposes to/from multiple websites in parallel,

2) have each taks/thread process info and write it to a central (shared) array of objects

3) then wait for a parallel tasks to finish

3) process the info collected on shared array data.


I'm assuming this is about correct usage of asynchronous queues, and some tricks with a synchronous/wait for completion method. need to see the handling of hte dance.

Also how to ensure the common global data object being written to safely from multiple parallel tasks.


pointers to example code much appreciated

Sorry I can't point you to any sample code off the top of my head, but this sounds like a perfect application of NSOperationQueue and operation dependencies. You could add an operation for each download. You can set the max concurrent operations to limit the number of concurrent requests but still have parallelism. You could add your processing operation with an operation dependency on each of the download operations so it wouldn't start until all the downloads were completed.


Posting sample code to show multi threading synchronization is fraught with peril anyway since every situation is different. But in general, if you are accessing a common data structure from multiple threads, you add a synchronization primitive around each and every access to that data structure (read or write), and try and ensure that you don't deadlock. Don't hold the lock while you're doing a long network operation, for example - do the network operation, then lock / update / unlock. I use Obj-C so I've been doing it with @synchronized or NSCondition. There are several other good synchronization APIs too though.

Seriously??? "u n l o c k" is a banned word?? Forum admins. Please return to sanity. This is a programming forum.

I generally recommend that folks start with Technote 2109 "Simple and Reliable Threading with NSOperation" and its associated ListAdder sample code.

<https://developer.apple.com/library/ios/#technotes/tn2109/_index.html>


<https://developer.apple.com/library/ios/#samplecode/ListAdder/>


Share and Enjoy

--

Quinn "The Eskimo!"

Apple Developer Relations, Developer Technical Support, Core OS/Hardware

Asynchronous Design Patterns with Blocks GCD
 
 
Q