Clicky

iOS Dev Nugget 142 Grand Central Dispatch

.

Need to run a code review on your codebase? Hire me

Grand Central Dispatch (GCD) lets you run tasks concurrently, taking advantage of multi-core processors.

For e.g. you can run some code in the main queue, asynchronously:

dispatch_async(dispatch_get_main_queue()) {
    //do something in main queue
}

Or in the global, concurrent, low priority queue:

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) {
    //do something that doesn't require priority
}

You can fire off several such tasks and they will run concurrently where possible:

for i in 0..<100 {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) {
        //do something with i
    }
}

GCD also makes it easier to manage concurrent tasks. It's common to want to perform an action after every one of the concurrent tasks has completed. For e.g. maybe you have finished generating thumbnails from a batch of photos and want to zip it up and upload that zip file somewhere. You can do this using dispatch groups:

var taskGroup = dispatch_group_create()
for i in 0..<100 {
    dispatch_group_enter(taskGroup) //+1
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_LOW, 0)) {
        //do something with i
        dispatch_group_leave(taskGroup) //-1
    }
}
dispatch_group_notify(taskGroup, dispatch_get_main_queue()) {
    //Do what needs to be done in the main queue after all the tasks has to be completed
}

Think of a dispatch group as representing a counter that is initially 0. dispatch_group_enter() increments that counter by 1 and dispatch_group_leave() decrements it by 1. Once the counter goes to zero, the block passed to dispatch_group_notify() gets called on the specified queue.

As mentioned in nugget #131, add the following so you can play with this in a Swift playground:

import UIKit
import XCPlayground
XCPSetExecutionShouldContinueIndefinitely()


Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No

.

.

Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter

.

View archives of past issues