Thursday, 23 July 2015

GCD - Grand Central Dispatch 


GCD (Grand Central Dispatch )is an office name of libdispatch , Which support concurrent execution of code on IOS and OSX.

Advantage of using GCD 

  • GCD can improve your app’s responsiveness by helping you defer computationally expensive tasks and run them in the background.
  • GCD provides an easier concurrency model than locks and threads and helps to avoid concurrency bugs.
  • GCD is not a threading library or a wrapper around threads
  • GCD uses threads, but like sunshine, the developer never suffers direct exposure
  • GCD is a concurrency library implemented via FIFO queues
  • GCD is just the marketing name for libdispatch :#include <dispatch/dispatch.h>

How to use GCD feature


whenever you want to run something in the background, you just call queue and pass in some code to run.
Grand Central Dispatch will handle all of the details for you – it will create a new thread if it needs to, or reuse an old one if one is available.

Different type of operation supported by GCD

  •   You can do sync or async block execution
  • The difference between sync and async is that with sync, your code will pause and wait for the block answer before running the following code, thus potentially freezing your UI if the execution time is long. Whereas with async, the code runs on and the block is returned asynchronously.                                                                              

 primary function used to create or get queue are
dispatch_queue_create       // create a serial or concurrent queue
dispatch_get_main_queue     // get the one and only main queue
dispatch_get_global_queue   // get one of the global concurrent queues
dispatch_get_current_queue  // DEPRECATED

dispatch_queue_get_label    // get the label of a given queue

Adding task to the queue

// Asynchronous functions
dispatch_async
dispatch_after
dispatch_apply
// Synchronous functions
dispatch_once
dispatch_sync

dispatch_async will submit a task to a queue and return  immediately.
dispatch_after returns immediately, but delays until the specified time to submit the task. 
dispatch_apply also returns immediately and the task is submitted multiple times.
dispatch_sync will submit a task to a queue, and returns only when the task completes. 
dispatch_once will submits a task once and only once over the application lifetime, returns when the block completes.

Basic guide line for creating the Queues


  • Use of the main queue should be restricted to tasks that require the main thread and must be short to prevent locking up the UI.
  • Each created serial queue should have a purpose.
  • Each created serial queue should be named/labeled appropriate to that purpose.
  • Tasks performed on the concurrent queues must be thread-safe.

Different Type of Queues available in GCD


    Serial queues :
   Task in the serial queue execute one at a time , each task starts only after the preceding task has finished.
  
   Concurrent Queues
   Tasks in concurrent queues are guaranteed to start in the order they were added…and that’s about all you’re guaranteed! Items can finish in       any order

 Types of Queues :

 1.main queue : This is a system provided serial queue. like any serial queue, tasks in this queue execute one at a time. However, it’s guaranteed that all tasks will execute on the main thread, which is the only thread allowed to update your UI. This queue is the one to use for sending messages to UIViews or posting notifications.

2. Global dispatch Queue : These are the system provided concurrent queues, currently four global queues of different priority namely background,low, default and high . Be aware that Apple’s APIs also use these queues. so any tasks you add won’t be the only ones on these queues.

3. You can create your own serial or concurrent type queues


    example for nested dispatching 

dispatch_queue_t background_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, NULL);
dispatch_async(background_queue, ^{
    // do some stuff that takes a long time here...

    // follow up with some stuff on the main queue
    dispatch_async(dispatch_get_main_queue(), ^{
        // Typically updating the UI on the main thread.
    });
});

In case asynchronous ,things to be consider while using GCD 
Critical section 
Race Condition
Deadlock
Thread Safe
Context Switch

Advance GCD topics are dispatch groups, semaphores, barriers


dispatch barriers

Dispatch barriers are a group of functions acting as a serial-style bottleneck when working with concurrent queues. Using GCD’s barrier API ensures that the submitted block is the only item executed on the specified queue for that particular time. This means that all items submitted to the queue prior to the dispatch barrier must complete before the block will execute.
When the block’s turn arrives, the barrier executes the block and ensures that the queue does not execute any other blocks during that time. Once finished, the queue returns to its default implementation. GCD provides both synchronous and asynchronous barrier functions.

when you would and wouldn’t 
  • Custom Serial Queue: A bad choice here; barriers won’t do anything helpful since a serial queue executes one operation at a time anyway.
  • Global Concurrent Queue: Use caution here; this probably isn’t the best idea since other systems might be using the queues and you don’t want to monopolize them for your own purposes.
  • Custom Concurrent Queue: This is a great choice for atomic or critical areas of code. Anything you’re setting or instantiating that needs to be thread safe is a great candidate for a barrier.
 dispatch_barrier_async( queue, block);

Dispatch Groups
Dispatch groups notify you when an entire group of tasks completes. These tasks can be either asynchronous or synchronous and can even be tracked from different queues. Dispatch groups also notify you in synchronous or asynchronous fashion when all of the group’s events are complete. Since items are being tracked on different queues, an instance of dispatch_group_t keeps track of the different tasks in the queues.

The GCD API provides two ways to be notified when all events in the group have completed.

dispatch_group_wait
dispatch_group_notify

Semaphores
Semaphores lets you control the access of multiple consumers into a finite amount of resources. For example, if you created a semaphore with a pool of two resources, at most only two threads could access the critical section at the same time. Other items that want to use the resource must wait in a queue (FIFO)

ispatch_semaphore_create => creates a semaphore with initial value
dispatch_semaphore_signal => increments the semaphore (send a semaphore signal)
dispatch_semaphore_wait => decrements the semaphore (wait for a semaphore signal)