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
});
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
});
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.
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().
man dispatch_main
, and you'll find the following: "Cocoa applications need not call dispatch_main(). Blocks submitted to the main queue will be executed as part of the "common modes" of the application's main NSRunLoop or CFRunLoop. However, blocks submitted to the main queue in applications using dispatch_main() are not guaranteed to execute on the main thread." –
Antonomasia 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.
dispatch_async(dispatch_get_main_queue(), block)
may execute on any thread. –
Veridical dispatch_main()
: dispatch_async(dispatch_get_main_queue(), ...)
did not execute in the main thread (consistently). Then, using a RunLoop, it executed on the main thread. The man page for dispatch does also not explicitly mention that it would execute on the main thread: "The dispatch framework provides a default serial queue for the application to use. This queue is accessed via the dispatch_get_main_queue() function." –
Veridical man dispatch_main
says " However, blocks submitted to the main queue in applications using dispatch_main() are not guaranteed to execute on the main thread." –
Aegis © 2022 - 2024 — McMap. All rights reserved.