Grand Central Dispatch (GCD) is a relatively new approach to multicore programming developed by Apple. It made its debut in Mac OS X 10.6 Snow Leopard, and was recently introduced to iOS 4.0.
GCD is an extremely efficient and powerful alternative to older technologies such as NSThread. Complicated asynchronous programming challenges such as data locking and resource theft are nearly completely handled by GCD.
There are lots of things that GCD can do for us, but this post will focus on some of the basics in order to get you multithreading in your iOS app.
Before we start, understand that a GCD queue is simply a block of code that you provide to GCD, which is then scheduled to run on either a system- or user-generated queue.
Declaring a queue.
This will return us a user-generated queue.
dispatch_queue_t myQueue = dispatch_queue_create("com.iphonedevblog.post", NULL);
Here, the first parameter is a label your queue is identified by, and the second parameter is where you would define attributes of the queue (this is currently unsupported, so pass NULL).
Executing a queue.
This will run our passed code asynchronously.
dispatch_async(myQueue, ^{ [self doSomething]; });
Here, we first pass the queue we created earlier, then we provide a block of code for our queue to run.
Declaring and executing a queue at once.
If you don’t need to keep a reference to the queue you’re about to run, you can achieve both of the above steps like this.
dispatch_async(dispatch_queue_create ("com.iphonedevblog.post", NULL), ^{ [self doSomething]; });
Suspending a queue.
Should you need to suspend a queue, you can call the following. Suspending a queue will prevent all blocks of code associated with that queue from running.
dispatch_suspend(myQueue);
Resuming a queue.
Don’t forget to resume a queue if you have suspended it. Suspension and resumption operates similarly to retain and release in memory management. Calling dispatch_suspend increments the suspension count, and calling dispatch_resume decrements it. Your queue will only start running again when the suspension count becomes zero.
dispatch_resume(myQueue);
Running code on the main thread from a queue.
Some operations cannot be performed on asynchronous queues, so we have to run these on the main thread (each application has one of these). It is imperative that all UI drawing is done on the main thread, as well as any calls to the NSNotificationCenter. Run the following code from another queue to access the main thread.
dispatch_sync(dispatch_get_main_queue(), ^{ [self dismissLoginWindow]; });
Note that calling dispatch_suspend (and therefore dispatch_resume) will not work on the main queue.
Overall.
We have just scratched the surface of what GCD can do, but what we’ve covered in this post should be enough to get you up and running and have you multithreading with ease.
For more information, start by reading Apple’s Grand Central Dispatch Technology Briefhere.
Happy coding,
Ricky.
@end