Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using dispatch_get_main_queue() mean that my code will be on the main thread?

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
});
like image 650
aryaxt Avatar asked May 11 '12 20:05

aryaxt


2 Answers

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.

like image 182
Jack Lawrence Avatar answered Nov 15 '22 01:11

Jack Lawrence


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().

like image 24
Patrick Perini Avatar answered Nov 15 '22 01:11

Patrick Perini