Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grand Central Dispatch async vs sync [duplicate]

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.

like image 939
C.Johns Avatar asked Feb 08 '12 20:02

C.Johns


People also ask

Is dispatch a sync or async?

Every dispatch queue has an async method that schedules a chunk of work that's in the closure it receives to be executed at a later time (asynchronously).

What is the difference between GCD and NSOperationQueue in iOS?

GCD is a low-level C-based API that enables very simple use of a task-based concurrency model. NSOperation and NSOperationQueue are Objective-C classes that do a similar thing. NSOperation was introduced first, but as of 10.5 and iOS 2, NSOperationQueue and friends are internally implemented using GCD .

What is DispatchGroup in Swift?

DispatchGroup is an object that can monitor all the concurrent tasks you want to track. Through execute group. enter when the task has started and execute group. leave when the task is complete, DispatchGroup can tell you which task has been completed, so you can execute the final task via calling group.


2 Answers

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

like image 91
jkh Avatar answered Sep 28 '22 03:09

jkh


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

like image 40
Tony Million Avatar answered Sep 28 '22 05:09

Tony Million