Using GCD with Blocks

GCD provides and manages FIFO queues to which your application can submit tasks in the form of block objects.

Queues are a C typedef viz. dispatch_queue_t. GCD offers three kinds of queues, main, concurrent and serial.

Main queue is automatically created by the system and associated with your application. You can get it by using dispatch_get_main_queue().

Concurrent queue can be created using dispatch_get_global_queue and it executes the tasks, submitted in the form of block in FIFO order, however, the tasks run concurrently and can finish in any order.

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);


Serial queues execute tasks in a strict FIFO serial order one at a time. To create serial queue use dispatch_queue_create which takes the name of the queue as first argument and options (currently NULL) as second argument.

dispatch_queue_create(“com.example.MyQueue”, NULL);

Submitting a block to Queue for Execution

You can submit a block to queue for execution using two of GCD provided functions:

dispatch_async OR dispatch_sync

Both the functions accept queue as the first argument and block as the second argument. dispatch_async returns immediately and executes the task asynchronously while dispatch_sync blocks execution until the provided block returns.

One good demonstration of using GCD API’s with concurrent and main queue and blocks is this blog entry from Jeff Kelly’s blog:

I also like Andy’s blog entry on testing or debugging block based API’s using the code snippet he created:

In fact, you can use Jeff’s idea of async loading of table cells along with Andy’s code snippet to test the async loading.






  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: