29

I'm reading the docs on dispatch queues for GCD, and in it they say that the queues are FIFO, so I am woundering what effect this has on async / sync dispatches?

from my understand async executes things in the order that it gets things while sync executes things serial..

but when you write your GCD code you decide the order in which things happen.. so as long as your know whats going on in your code you should know the order in which things execute..

my questions are, wheres the benefit of async here? am I missing something in my understanding of these two things.

C.Johns
  • 10,185
  • 20
  • 102
  • 156

4 Answers4

40

The first answer isn't quite complete, unfortunately. Yes, sync will block and async will not, however there are additional semantics to take into account. Calling dispatch_sync() will also cause your code to wait until each and every pending item on that queue has finished executing, also making it a synchronization point for said work. dispatch_async() will simply submit the work to the queue and return immediately, after which it will be executed "at some point" and you need to track completion of that work in some other way (usually by nesting one dispatch_async inside another dispatch_async - see the man page for example).

jkh
  • 3,246
  • 16
  • 13
23

sync means the function WILL BLOCK the current thread until it has completed, async means it will be handled in the background and the function WILL NOT BLOCK the current thread.

If you want serial execution of blocks check out the creation of a serial dispatch queue

Tony Million
  • 4,296
  • 24
  • 24
  • ah yea that clears it up cool thanks for that. Yes I am using serial queues now.. I just wasnt sure where the benefit was now I do. thanks. – C.Johns Feb 08 '12 at 20:18
9

From the man page:

FUNDAMENTALS

Conceptually, dispatch_sync() is a convenient wrapper around dispatch_async() with the addition of a semaphore to wait for completion of the block, and a wrapper around the block to signal its completion.

See dispatch_semaphore_create(3) for more information about dispatch semaphores. The actual implementation of the dispatch_sync() function may be optimized and differ from the above description.

Marko
  • 2,778
  • 2
  • 10
  • 19
Anonymous
  • 456
  • 3
  • 2
5

Tasks can be performed synchronously or asynchronously.

Synchronous function returns the control on the current queue only after task is finished. It blocks the queue and waits until the task is finished.

Asynchronous function returns control on the current queue right after task has been sent to be performed on the different queue. It doesn't wait until the task is finished. It doesn't block the queue.

Only in Asynchronous we can add delay -> asyncAfter(deadline: 10..

Vinoth Anandan
  • 1,157
  • 17
  • 15