iOS Multithreading

Notes from Lecture 9 — Stanford CS193P

To execute a function on another queue

let queue: dispatch_queue_t = something
dispatch_async(queue){/*do stuff here}

Creating a main queue (a serial queue)

  • Do all the UI stuff in this queue
  • Do all the non-UI, time consuming stuff not on this queue.
  • dispatch_async simply puts your function in the queue
let mainQ: dispatch_queue_t = dispatch_get_main_queue()

common code to write:

dispatch_async(not the main queue){
//do a non-UI that might block or otherwise takes a while
dispatch_async(dispatch_get_main_queue()){
//call UI functions with the results of the above
}
}

Other concurrent queues (not the main queue)

  • QOS_CLASS_USER_INTERACTIVE — quick and high priority
  • QOS_CLASS_USER_INITIATED — high priority, might take time
  • QOS_CLASS_UTILITY — long running
  • QOS_CLASS_BACKGROUND — user not concerned with this (prefetching, etc)

usage:

  • let queue = dispatch_get_global_queue(<one of the above, 0) // 0 means reserved for future”

Creating your own serial queue:

let serialQ = dispatch_queue_create(“name”, DISPATCH_QUEUE_SERIAL)
  • For when you want to throttle your access to the network/downloading a bunch of things from a website but don’t want to deluge that website, so you queue the requests up serially.

There is an object-oriented API to all of this

*NSOperationQueue and NSOperation