Question

Does the following code run on the main thread? Does "main queue" refer to the main thread?

dispatch_async(dispatch_get_main_queue(),
^{
   // Some code
});
Was it helpful?

Solution

The async part of dispatch async vs sync is different than concurrent vs serial. Async means that the function returns immediately, sync means that it'll wait until the block is executed. Since the main thread/queue is serial, things are going to get executed in order - I believe this means that since you're asking it to async dispatch on the same thread you're dispatching from, it'll return immediately, wait till the end of the current run loop and anything else in the queue, and then execute your block.

This is more useful for inside a queue than it is on the main thread - you can process your data, let the UI know to update, and continue processing without waiting for everything to redraw, etc. That's why you'll often see a dispatch_async call to the main thread inside another dispatch_async(concurrent queue) instead of just a dispatch_sync.

OTHER TIPS

Yes. From Apple developer site:

The dispatch framework provides a default serial queue for the application to use. This queue is accessed via dispatch_get_main_queue().

This is documented in multiple places, including the docs for dispatch_get_main_queue() itself. The Concurrency Programming Guide says:

The main dispatch queue is a globally available serial queue that executes tasks on the application’s main thread.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top