Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is purpose of dispatch sync?

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.

like image 726
Stefan Avatar asked Oct 19 '22 03:10

Stefan


2 Answers

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                           [....]

like image 143
RTasche Avatar answered Nov 15 '22 03:11

RTasche


The purpose of dispatch_syncqueue 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

like image 20
Saheb Roy Avatar answered Nov 15 '22 05:11

Saheb Roy