I understand that dispatch_async()
runs something on a background thread, and dispatch_main()
runs it on the main thread, so where does dispatch_sync()
come in?

- 63,694
- 13
- 151
- 195

- 29,668
- 57
- 204
- 388
-
3This question indicates that you might not have seen the conceptual documentation for GCD, which would cover all these things: https://developer.apple.com/library/mac/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ConcurrencyandApplicationDesign/ConcurrencyandApplicationDesign.html – ipmcc Jan 14 '14 at 19:25
-
1See also [Concurrent vs serial queues in GCD](http://stackoverflow.com/q/19179358), [Concurrency and serial queues in Grand Central Dispatch](http://stackoverflow.com/q/5026043) – jscs Jan 14 '14 at 19:29
2 Answers
You don't generally want to use dispatch_main()
. It's for things other than regular applications (system daemons and such). It is, in fact, guaranteed to break your program if you call it in a regular app.
dispatch_sync
runs a block on a queue and waits for it to finish, dispatch_async
runs a block on a queue and doesn't wait for it to finish.
Serial queues run one block at a time, in order. Concurrent queues run multiple blocks at a time, and therefore aren't necessarily in order.
(edit)
Perhaps when you said dispatch_main()
you were thinking of dispatch_get_main_queue()
?

- 41,261
- 11
- 67
- 84
dispatch_main()
is not for running things on the main thread — it runs the GCD block dispatcher. In a normal app, you won't need or want to use it.
dispatch_sync()
blocks the current thread until the block completes. This may or may not be the main thread.
If you want to run something on the main thread, you can use dispatch_get_main_queue()
to get the main queue and use once of the normal dispatch methods to run a block there.

- 234,037
- 30
- 302
- 389