Skip to main content

dispatch_async vs dispatch_sync

GCD:

A library to provide support for concurrent code execution on multicore hardware in iOS. It provides an easier mechanism to access multi-thread environment without taking the overhead of lock and unlock shared data, create a thread and perform a task like that.

If we use  NSThread or pthread in the application then we need to take care of so much point. Like if I need to execute 10 tasks concurrently in my application. How much thread pool I require, how to synchronise two tasks while using threads.

It provides methods to add a task in a queue.

1) Dispatch Async
2) Dispatch Sync 

Dispatch Async:

This method is used to add a block for asynchronous execution and return immediately. If you used this method to add a block then it will return immediately and does not wait for execution of the block.

If you do not want to wait for the execution of the block then you can use this method to add operation in a dispatch queue.

- (void) performMyTask{
     dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //Your block task
        for (NSUInteger i=0; i < 100;i++) {
            NSLog(@"Block %lu", (unsigned long)i);
        }
    });
    //Task 1
    NSLog(@"Task1");
}

What will be the output here?

1) Task 1 print first then all block value 0..99
2) First All block value 0..99 and Then Task 1
3) Cannot Determine the behaviour

The solution is Option 3 you cannot determine the behaviour, in this case, it totally depends on when the global queue picks the task and execute it.

Dispatch Sync:

This method is used to add a block for synchronous execution and wait until execution is completed.
i.e. It blocks the current thread If you used this method then the function will not return until your block is not executed fully. If you want to wait for your block execution you can use this method.

- (void) performMyTask{
    dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //Your block task
        for (NSUInteger i=0; i < 100;i++) {
            NSLog(@"Block %lu", (unsigned long)i);
        }
    });
    //Task 1
    NSLog(@"Task1");
}

What will be the output here?

1) Task 1 print first then all block value 0..99
2) First All block value 0..99 and Then Task 1
3) Cannot Determine the behaviour

The solution is Option 2 the behaviour is well defined in this case method will not return until the block is not executed. So all the block value is executed first then the Task1.

What will happen?

If I use dispacth_sync on the main queue in the view controller life cycle method?

- (void) viewDidLoad{
    dispatch_sync(dispatch_get_main_queue(), ^{
        //Your block task
        for (NSUInteger i=0; i < 100;i++) {
            NSLog(@"Block %lu", (unsigned long)i);
        }
    });
    //Task 1
    NSLog(@"Task1");
}

Your application will crash or become unresponsive because of the deadlock cycle. Dispatch block waits for the main queue to be free and the main queue is blocked to execute the dispatched task.

More Dispatch Sync


Comments

Popular posts from this blog

What does enable bitcode do in Xcode

Background: Now days compilation process for any language is divided into two parts and same is applicable for objective c. Frontend Compiler (Clang) Backend Compiler (LLVM) Frontend Compiler (Clang):  Responsibility of front-end compiler is to take a source code and convert into intermediate representation (IR).  In case of clang it is LLVM IR.  Backend Compiler(LLVM):  Responsibility of backend compiler is to take a IR as input and convert into object code. LLVM input is bitstream of LLVM IR (Bitcode) and output is sequence of machine instruction(Object code). Each  cpu or processor has different set of  M achine   instruction, So  LLVM output is CPU dependent or it can be executed on specific CPU only.   There may be question in your mind that  1) What is the need to divide into these phases? 2) What is LLVM IR? Can we see the LLVM IR as Output? What is the need to divide into these phases? It is beneficial for both the programming language designer a

Asynchronous Request with NSOperationQueue

Today post is about how to run a asynchronous task in NSOperationQueue.  Generally we do not run a Asynchronous task in NSOperationQueue. It is also not recommended for any programmer to do that. This post is only for learning purpose what will happen if we schedule a asynchronous task in a queue and how can we complete that task:). So let us move to the learning: NSOperationQueue: In iOS NSOperationQueue is a class, which provide a way to perform operation concurrently. We also have others way to perform concurrent operation: 1) GCD 2) NSThread 3) pThread NSOperationQueue is a wrapper on GCD, which provides a very convenient way to execute operation concurrently. To create a Queue for Operation you have to simply allocate a object of the class: NSOperationQueue * opertionQueue = [[ NSOperationQueue alloc ] init ]; For this post let suppose you are making a queue to handle all Http request in your application. So i want to create a queue in Handler class

Everything about BLE with iOS Part1 (Introduction)

In this article we will learn how to turn your iPhone to behave as peripheral (who has data to send) or central (who receive the data). What is BLE (Bluetooth Low energy device) ? Bluetooth LE is a wireless personal area network technology like its previous incarnation, Classic Bluetooth. It can be use to transfer and receiving of the data. What is difference between Classic and LE ? BLE has low power consumption and low data transfer rate. BLE can support large number of slaves. On the other hand Classic (3.0) support maximum 7 devices connectivity. Unique feature of BLE is advertising  functionality,  So other devices can scan,  connect and  receive data from the advertising BLE device. Other difference is in classic you need to pair the devices first for the communication. Terms: Peripheral:  It is device which advertise the service. In client-server architecture form we can say peripheral is server which has data to send to client. The basic difference i