I’m trying to understand this common pattern:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
// Background stuff on background thread
dispatch_async(dispatch_get_main_queue()) {
// Update UI on main thread
}
}
The Apple literature states:
Completion callbacks can be accomplished via nested calls to the dispatch_async() function.
Ok, but I thought the FIFO aspect of dispatch_async
was that it guarantees that tasks start in the order submitted. I thought it didn't guarantee that they would complete in any order?
My question is, why does the nested call wait for the completion of the closure/block it's nested in?
If I were to write
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
doThing1()
doThing2()
doThing3()
}
would that guarantee that doThing2()
would wait until the execution of doThing1()
before executing? If so, does this mean that it's equivalent to two subsequent dispatch_sync calls, like this:
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
doThing1()
}
dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
doThing2()
}
?