Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Grand Central Dispatch (GCD)
Grand Central Dispatch (GCD) is a technology for Apple's Mac OS X and iOS operating systems that provides a combination of extensions to the C language, an API, and a runtime library. It allows application developers to identify sections of code to run in parallel, managing most of the threading details automatically like OpenMP.
Syntax
// Block syntax
^{ /* code block */ }
// Dispatch queue creation
dispatch_queue_t dispatch_get_global_queue(long identifier, unsigned long flags);
// Async execution
void dispatch_async(dispatch_queue_t queue, dispatch_block_t block);
Blocks in GCD
GCD introduces extensions to the C and C++ languages known as blocks. A block is a self−contained unit of work specified by a caret ^ inserted in front of braces { }.
^{
printf("This is a block");
}
Dispatch Queues
GCD schedules blocks for execution by placing them on dispatch queues. It identifies two types of dispatch queues −
- Serial Queue: Blocks are removed in FIFO order and execute sequentially. Each process has a main queue (serial).
- Concurrent Queue: Multiple blocks can be removed simultaneously, allowing parallel execution.
Example: Using Concurrent Queue
The following example demonstrates obtaining a default−priority concurrent queue and submitting a block using dispatch_async() −
#include <stdio.h>
#include <dispatch/dispatch.h>
int main() {
// Get default priority concurrent queue
dispatch_queue_t queue = dispatch_get_global_queue(
DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
// Submit block to queue asynchronously
dispatch_async(queue, ^{
printf("This block executes concurrently.<br>");
});
// Wait for completion (simplified example)
dispatch_main();
return 0;
}
Priority Levels
GCD provides three system−wide concurrent dispatch queues distinguished by priority −
| Priority Level | Constant | Usage |
|---|---|---|
| High | DISPATCH_QUEUE_PRIORITY_HIGH | Critical tasks |
| Default | DISPATCH_QUEUE_PRIORITY_DEFAULT | Normal tasks |
| Low | DISPATCH_QUEUE_PRIORITY_LOW | Background tasks |
Key Features
- GCD's thread pool is composed of POSIX threads
- Actively manages thread pool size based on application demand
- Provides automatic load balancing and resource management
- Blocks with higher priority should use high−priority queues
Conclusion
Grand Central Dispatch simplifies parallel programming by providing an efficient block−based approach to concurrency. It automatically manages threading details while allowing developers to focus on defining work units through blocks and appropriate queue selection.
