iosobjective-casynchronoussynchronousdispatch-async

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.


Solution

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