iOS Grand Central Dispatch

GCD provides three main types of queues:

1.1 Main queue

Main queue runs on the main thread and is a serial queue.
This is a common choice to update the UI after completing work in a task on a concurrent queue. To do this, you’ll code one closure inside another. Targeting the main queue and calling async guarantees that this new task will execute sometime after the current method finishes.

// Get the main queue
let mainQueue = DispatchQueue.main

1.2 Global queues

This is a common choice to perform non-UI work in the background.
Global queques are Concurrent queues that are shared by the whole system. There are four such queues with different priorities : high, default, low, and background. The background priority queue is I/O throttled.

// Get the .userInitiated global dispatch queue
let userQueue = DispatchQueue.global(qos: .userInitiated)
// Get the .default global dispatch queue
let defaultQueue = DispatchQueue.global()

When setting up the global concurrent queues, you don’t specify the priority directly. Instead you specify a Quality of Service (QoS) class property. This will indicate the task’s importance and guide GCD into determining the priority to give to the task.

The QoS classes are:

  • User-interactive
    This represents tasks that need to be done immediately in order to provide a nice user experience. Use it for UI updates, event handling and small workloads that require low latency. The total amount of work done in this class during the execution of your app should be small. This should run on the main thread.

  • User-initiated
    The represents tasks that are initiated from the UI and can be performed asynchronously. It should be used when the user is waiting for immediate results, and for tasks required to continue user interaction. This will get mapped into the high priority global queue.

DispatchQueue.global(qos: .userInitiated).async { // 1
  let overlayImage = self.faceOverlayImageFromImage(self.image)
  DispatchQueue.main.async { // 2
    self.fadeInNewImage(overlayImage) // 3
  }
}
  • Utility
    This represents long-running tasks, typically with a user-visible progress indicator. Use it for computations, I/O, networking, continuous data feeds and similar tasks. This class is designed to be energy efficient. This will get mapped into the low priority global queue.

  • Background
    This represents tasks that the user is not directly aware of. Use it for prefetching, maintenance, and other tasks that don’t require user interaction and aren’t time-sensitive. This will get mapped into the background priority global queue.

1.3 Custom queues

Queues that you create which can be serial or concurrent. These actually trickle down into being handled by one of the global queues.

  • Serial Queue
    The only global serial queue is DispatchQueue.main, but you can create a private serial queue. Note that .serial is the default attribute for a private dispatch queue:
// Create mySerialQueue
let mySerialqueue = DispatchQueue(label: "com.tang.max")
  • Concurrent Queue
    A good choice when you want to perform background work serially and track it. This eliminates resource contention since you know only one task at a time is executing. Note that if you need the data from a method, you must inline another closure to retrieve it or consider using sync.
    To create a private concurrent queue, specify the .concurrent attribute.
// Create workerQueue
let workerQueue = DispatchQueue(label: "com.tang.max", qos: .background, attributes: .concurrent, autoreleaseFrequency: .inherit, target: nil)

Synchronous vs. Asynchronous

With GCD, you can dispatch a task either synchronously or asynchronously.
A synchronous function returns control to the caller after the task is completed.
An asynchronous function returns immediately, ordering the task to be done but not waiting for it. Thus, an asynchronous function does not block the current thread of execution from proceeding on to the next function.

Delaying Task Execution

DispatchQueue allows you to delay task execution. Care should be taken not to use this to solve race conditions or other timing bugs through hacks like introducing delays. Use this when you want a task to run at a specific time.
Consider the user experience of your app for a moment. It’s possible that users might be confused about what to do when they open the app for the first time — were you? :]
It would be a good idea to display a prompt to the user if there aren’t any photos. You should also consider how the user’s eyes will navigate the home screen. If you display a prompt too quickly, they might miss it as their eyes linger on other parts of the view. A one-second delay before displaying the prompt should be enough to catch the user’s attention and guide them.

let delayInSeconds = 1.0 // 1
DispatchQueue.main.asyncAfter(deadline: .now() + delayInSeconds) { // 2
  let count = PhotoManager.sharedManager.photos.count
  if count > 0 {
    self.navigationItem.prompt = nil
  } else {
    self.navigationItem.prompt = "Add photos with faces to Googlyify them!"
  }
}

Part 2: Operation Queues

GCD is a low-level C API that enables developers to execute tasks concurrently. Operation queue, on the other hand, is high level abstraction of the queue model, and is built on top of GCD. That means you can execute tasks concurrently just like GCD, but in an object-oriented fashion. In short, operation queues just make developers’ life even simpler.

Unlike GCD, they don’t conform to the First-In-First-Out order. Here are how operation queues are different from dispatch queues:

  • Don’t follow FIFO: in operation queues, you can set an execution priority for operations and you can add dependencies between operations which means you can define that some operations will only be executed after the completion of other operations. This is why they don’t follow First-In-First-Out.
  • By default, they operate concurrently: while you can’t change its type to serial queues, there is still a workaround to execute tasks in operation queues in sequence by using dependencies between operations.
  • Operation queues are instances of class OperationQueue and its tasks are encapsulated in instances of Operation.

2.1 Operation

Tasks submitted to operation queues are in the form of Operation instances. You can simply think of Operation as a single unit of work.
Operation is an abstract class which can’t be used directly so you have to use Operation subclasses.

Here’s a quick comparison of the two that will help you decide when and where to use GCD or Operation:

  • GCD is a lightweight way to represent units of work that are going to be executed concurrently. You don’t schedule these units of work; the system takes care of scheduling for you. Adding dependency among blocks can be a headache. Canceling or suspending a block creates extra work for you as a developer! :]
  • Operation adds a little extra overhead compared to GCD, but you can add dependency among various operations and re-use, cancel or suspend them.
  • A stand alone Operation runs synchronously. To run it off the main queue, we have to dispatch it to a queue, ,either to a dispatch queue or an Operation
open class Operation : NSObject {
    open func start()
    open func main()
    open var isCancelled: Bool { get }
    open func cancel()
    open var isExecuting: Bool { get }
    open var isFinished: Bool { get }
    open var isConcurrent: Bool { get }

    @available(iOS 7.0, *)
    open var isAsynchronous: Bool { get }

    open var isReady: Bool { get }
    open func addDependency(_ op: Operation)
    open func removeDependency(_ op: Operation)
    open var dependencies: [Operation] { get }
    open var queuePriority: Operation.QueuePriority
    
    @available(iOS 4.0, *)
    open var completionBlock: (() -> Swift.Void)?

    @available(iOS 4.0, *)
    open func waitUntilFinished()
    
    @available(iOS, introduced: 4.0, deprecated: 8.0, message: "Not supported")
    open var threadPriority: Double
    
    @available(iOS 8.0, *)
    open var qualityOfService: QualityOfService

    @available(iOS 8.0, *)
    open var name: String?
}

In the iOS SDK, we are provided with two concrete subclasses of Operation. These classes can be used directly, but you can also subclass Operation and create your own class to perform the operations. The two classes that we can use directly are:

  • BlockOperation – A BlockOperation is just a wrapper of around the default global dispatch queue, it manages the concurrent execution of one or more blocks on the default global queue. This class provides an object oriented wrapper for the apps that are already using object Operation queues and don't want to create dispatch queues as well. But being an Operation, it has more features than a dispatch queue task. It can take advantage of Operation dependencies, KVO notifications and cancelling. A BlockOperation also behaves like a dispatch group, it marks itself as finished when all its blocks have finished executing. So you can use it to track a group of executing blocks. BlockOperation blocks run concurrently, synchronously, if you need to execute blocks serially, submit them directly to a private dispatch queue, or set them up with dependencies.
  • InvocationOperation – Use this class to initiate an operation that consists of invoking a selector on a specified object.

So what’s the advantages of Operation?

  • First, they support dependencies through the method addDependency(op: Operation) in the Operation class. When you need to start an operation that depends on the execution of the other, you will want to use Operation.

  • Secondly, you can change the execution priority by setting the property queuePriority with one of these values. The operations with high priority will be executed first.

    public enum OperationQueuePriority : Int {
        case VeryLow
        case Low
        case Normal
        case High
        case VeryHigh
    }
    
  • You can cancel a particular operation or all operations for any given queue. The operation can be cancelled after being added to the queue. Cancellation is done by calling method cancel() in the Operation class. When you cancel any operation, we have three scenarios that one of them will happen:

    • Your operation is already finished. In that case, the cancel method has no effect.
    • Your operation is already being executing. In that case, system will NOT force your operation code to stop but instead, cancelled property will be set to true.
    • Your operation is still in the queue waiting to be executed. In that case, your operation will not be executed.
  • Operation has 3 helpful boolean properties which are finished, cancelled, and ready. finished will be set to true once operation execution is done. cancelled is set to true once the operation has been cancelled. ready is set to true once the operation is about to be executed now.

  • Any Operation has an option to set completion block to be called once the task being finished. The block will be called once the property finished is set to true in Operation.

For example:

@IBAction func didClickOnStart(sender: AnyObject) {
    queue = OperationQueue()

    queue.addOperationWithBlock { () -> Void in
        
        let img1 = Downloader.downloadImageWithURL(imageURLs[0])

        OperationOperationQueue.mainQueue().addOperationWithBlock({
            self.imageView1.image = img1
        })
    }
    
    queue.addOperationWithBlock { () -> Void in
        let img2 = Downloader.downloadImageWithURL(imageURLs[1])
        
        OperationQueue.mainQueue().addOperationWithBlock({
            self.imageView2.image = img2
        })

    }
    
    queue.addOperationWithBlock { () -> Void in
        let img3 = Downloader.downloadImageWithURL(imageURLs[2])
        
        OperationQueue.mainQueue().addOperationWithBlock({
            self.imageView3.image = img3
        })

    }
    
    queue.addOperationWithBlock { () -> Void in
        let img4 = Downloader.downloadImageWithURL(imageURLs[3])
        
        OperationQueue.mainQueue().addOperationWithBlock({
            self.imageView4.image = img4
        })

    }
}

How we can use NSBlockOperation to do the same, but at the same time, giving us more functionalities and options such as setting completion handler. The didClickOnStart method is rewritten like this:

@IBAction func didClickOnStart(sender: AnyObject) {
    
    queue = OperationQueue()
    let operation1 = NSBlockOperation(block: {
        let img1 = Downloader.downloadImageWithURL(imageURLs[0])
        OperationQueue.mainQueue().addOperationWithBlock({
            self.imageView1.image = img1
        })
    })
    
    operation1.completionBlock = {
        print("Operation 1 completed")
    }
    queue.addOperation(operation1)
    
    let operation2 = NSBlockOperation(block: {
        let img2 = Downloader.downloadImageWithURL(imageURLs[1])
        OperationQueue.mainQueue().addOperationWithBlock({
            self.imageView2.image = img2
        })
    })
    
    operation2.completionBlock = {
        print("Operation 2 completed")
    }
    queue.addOperation(operation2)
    
    
    let operation3 = NSBlockOperation(block: {
        let img3 = Downloader.downloadImageWithURL(imageURLs[2])
        OperationQueue.mainQueue().addOperationWithBlock({
            self.imageView3.image = img3
        })
    })
    
    operation3.completionBlock = {
        print("Operation 3 completed")
    }
    queue.addOperation(operation3)
    
    let operation4 = NSBlockOperation(block: {
        let img4 = Downloader.downloadImageWithURL(imageURLs[3])
        OperationQueue.mainQueue().addOperationWithBlock({
            self.imageView4.image = img4
        })
    })
    
    operation4.completionBlock = {
        print("Operation 4 completed")
    }
    queue.addOperation(operation4)
}

For each operation, we create a new instance of NSBlockOperation to encapsulate the task into a block. By using NSBlockOperation, you’re allowed to set the completion handler. Now when the operation is done, the completion handler will be called. For simplicity, we just log a simple message to indicate the operation is done. If you run the demo, you would see something like this in console:

Operation 1 completed
Operation 3 completed
Operation 2 completed
Operation 4 completed

2.2 Canceling Operations

As mentioned before, NSBlockOperation allows you to manage the operations:



operation2.addDependency(operation1)
operation3.addDependency(operation2)

operation1.completionBlock = {
    print("Operation 1 completed, cancelled:\(operation1.cancelled) ")
}
// ...

queue.cancelAllOperations()

General advice

  • One QoS for tasks accessing shared resource
  • Serial queue to access shared resource
  • Avoid Operation dependency cycles
  • Be careful when calling sync()
  • Never call sync() on the current queue
  • Never ever call sync from the main queue
    *

Reference:
Grand Central Dispatch Tutorial for Swift 3(1)
Grand Central Dispatch Tutorial for Swift 3(2)
iOS Concurrency: Getting Started with NSOperation and Dispatch Queues
Apple’s Concurrency Guide
iOS Concurrency repository on Github

About Tang

A mobile developer, work in Stockholm, Sweden
This entry was posted in iOS and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s