I'm pretty clear what dispatch_async queue is performing, but I'm not clear what dispatch_sync purpose is. For an example: what is difference between this:
NSLog(@"A");
NSLog(@"B");
and this:
dispatch_sync(dispatch_get_main_queue(), ^ {
NSLog(@"A");
});
NSLog(@"B");
As I get, in both ways output will be A then B. Because sync is executed in order that is written. Thanks.
As the names says dispatch_sync
makes it possible to synchronize the tasks to be executed even if they are not executed on the main queue.
Saheb Roy's answer is only half of the truth. You can only specify the dispatch queue your code should be executed on. The actual thread is chosen by GCD.
Code blocks dispatched using dispatch_async on a concurrent queue are also executed in the FIFO way and guaranteed to be executed in the order you dispatch them. The main difference is that dispatch_sync on a serial queue also guarantees you that following code blocks are not executed before the previous block has finished executing. dispatch_sync
is blocking your current dispatch queue i.e. the queue your dispatch_sync call is executed on. So your calling function is blocked until the dispatched code block returns whereas dispatch_async
returns immediately.
execution timeline using dispatch_async
on a concurrent queue my look like this:
Block A [..............]
Block B [.....]
Block C [....]
while using dispatch_sync
on a serial queue looks like this:
Block A [..............]
Block B [.....]
Block C [....]
The purpose of dispatch_sync
queue is that it will dispatch blocks of code in the thread you mentioned and that the will run synchronously, meaning one by one or rather one after the other in FIFO method.
Do check out NSOperationQueue
to understand the function of dispatch_sync
in a better way
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With