SlideShare a Scribd company logo
Grand Central Dispatch
Ben Asher
basher@yelp.com
benasher44 on Github and Twitter
Yelp’s Mission:
Connecting people with great
local businesses.
2
Yelp Stats:
As of Q2 2015
83M 3268%83M
3
A Responsive App
- Responsive UI
- Don’t make the user wait
4
GCD - Getting Started
Basics of blocks in Objective-C
5
- Segment of code
- Passed around as parameters
- Stored in variables
- Called like C functions ()
^{
// Some code
};
What is GCD about?
“…technology that you use to manage the
execution of tasks in your app…”
- Apple Docs
6
- C API (mostly)
- Open source!
- Task = ^{}
GCD - Intro
7
- Schedule tasks
- dispatch_queue
- Synchronize tasks
- dispatch_group
- Serialize asynchronous tasks
- dispatch_suspend and dispatch_resume
GCD Techniques
8
Scheduling Tasks with GCD
GCD - Scheduling Tasks with Queues
Queues
Serial
Concurrent
10
GCD - Scheduling Tasks with Queues
Queues
^{1}^{2}
^{1}^{2}^{3}
^{3}
11
dispatch_queue_t dispatch_queue_create(
const char *label,
dispatch_queue_attr_t attr
);
dispatch_queue_create(“q”, DISPATCH_QUEUE_SERIAL);
dispatch_queue_create(“q”, DISPATCH_QUEUE_CONCURRENT);
GCD - Scheduling Tasks with Queues
12
Quality of Service Class
- Urgency of queued tasks
- Relative priority
GCD - Scheduling Tasks with Queues
iOS 8+
QOS_CLASS_USER_INTERACTIVE
QOS_CLASS_USER_INITIATED
QOS_CLASS_DEFAULT
QOS_CLASS_UTILITY
QOS_CLASS_BACKGROUND
13
GCD - Scheduling Tasks with Queues
iOS 8+
QOS_CLASS_USER_INTERACTIVE
QOS_CLASS_USER_INITIATED
QOS_CLASS_DEFAULT
QOS_CLASS_UTILITY
QOS_CLASS_BACKGROUND
14
dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL,
QOS_CLASS_UTILITY,
0);
QOS_CLASS_USER_INITIATED
QOS_CLASS_UTILITY
- 5 Global Queues
- 1 per QOS class
- Concurrent, background thread
GCD - Scheduling Tasks with Queues
dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0);
15
Queues can target other queues
- (a) dispatch_queue_create(“q”, DISPATCH_QUEUE_SERIAL);
GCD - Scheduling Tasks with Queues
^{2}^{3} ^{1}
(a)
16
(b)
- (b) Global QOS_CLASS_DEFAULT
GCD - Scheduling Tasks with Queues
^{3} ^{2} ^{1}
dispatch_set_target_queue(someQ, targetQ);
(a) (b)
17
GCD - Scheduling Tasks with Queues
18
QOS_CLASS_UTILITY
QOS_CLASS_USER_INITIATED
GCD - Scheduling Tasks with Queues
Task
- dispatch_block_t b = ^{};
Schedule a task in GCD
- dispatch_sync(queue, ^{}) // Blocking
- dispatch_async(queue, ^{}) // Non blocking
19
GCD - Scheduling Tasks with Queues
- Special 6th global queue - main queue
- dispatch_get_main_queue()
- Executes blocks on the main thread
20
GCD - Scheduling Tasks with Queues
Common Pattern
dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT), ^{
// do some expensive work
dispatch_async(dispatch_get_main_queue(), ^{
// show user the work i did
});
});
21
Demo
Cat Pyramid
Synchronizing Tasks with GCD
GCD - Synchronizing Tasks
Problem - User generated video
- 2 tasks:
- Crop video
- Generate thumbnails for
keyframe slider
24
GCD - Synchronizing Tasks
Potential Solution - BOOL Flags
- isVideoProccessed
- areSliderImagesGenerated
- (void)hideLoadingIfPossible {
if (self.isVideoProcessed &&
self.areSliderImagesGenerated) {
// Hide the loading spinner
}
} 25
GCD - Synchronizing Tasks
Potential Solution - BOOL Flags
- (void)hideLoadingIfPossible {
if (self.isVideoProcessed &&
self.areSliderImagesGenerated &&
self.isAudioProcessed &&
self.isUserReadyToSeeThis
self.areYouSureUserIsReady) {
// Hide the loading spinner
}
}
26
Better Solution - Dispatch Groups
dispatch_group_t
- dispatch_group_create();
- Creates a new empty group
- dispatch_group_enter(group);
- Increments the number of tasks in group
- dispatch_group_leave(group);
- Decrements the number of tasks in group
GCD - Synchronizing Tasks
27
Potential solution - Dispatch Groups
dispatch_group_t group = dispatch_group_create();
// For each task:
// call dispatch_group_enter(group) on start
// call dispatch_group_leave on tasks completion
// Call wait to block until task count is 0
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
GCD - Synchronizing Tasks
28
Potential solution - Dispatch Groups
dispatch_group_t group = dispatch_group_create();
// For each task:
// call dispatch_group_enter(group) on start
// call dispatch_group_leave on tasks completion
dispatch_async(someConcurrentQueue, ^{
// Call wait to block until task count is 0
dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
});
GCD - Synchronizing Tasks
29
GCD - Synchronizing Tasks
Optimal Solution
- dispatch_group_notify(group, queue, block);
- Read “When there are no tasks left associated with this group, notify by
enqueueing this block onto this queue”
30
Demo
Cat Pyramid - Faster
Serialize Asynchronous Tasks
Sync Task
- Easily fits into a block
- Blocks until the task is done
Async Task
- Task happens in another thread/process
- Starting this task returns immediately
GCD - Serialize Async Tasks
33
Problem - Animations
GCD - Serialize Async Tasks
34
GCD - Serialize Async Tasks
Problem - Animations
[UIView animateWithDuration:1.0 animations:^{
// Rotate 90 degrees
} completion:^(BOOL finished) {
[UIView animateWithDuration:0.5 animations:^{
// Move down the screen 100pt
} completion:NULL];
}];
35
Demo
Fun with Animation Queueing
GCD - Caveats
Cleanup is hard
- if a dispatch_group_t is deallocated with a non-
zero task count, it will throw an exception
- dispatch_async
“…The queue is retained by the system until the block
has run to completion…” - Apple Docs
37
Tools in the Toolbelt
GCD
- Small synchronous tasks
- Simple asynchronous tasks
NSOperation and NSOperationQueue
- Complex asynchronous tasks
- Cancel support
38
What else can I do with GCD?
- Efficient reader/writer schemes
- dispatch_barrier
- Read and write data efficiently
- dispatch_io (disk) and dispatch_data (memory)
- Respond to low-level system objects
- dispatch_source
39
Resources
GCD Source
- https://libdispatch.macosforge.org/trac/browser/trunk
GCD Documentation
- https://developer.apple.
com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/
Demo App
- https://github.com/benasher44/SGConf2015Demo
40

More Related Content

PDF
Tech Talk #4 : Multi - threading and GCD ( grand central dispatch ) in iOS - ...
PDF
GCD and OperationQueue.
PPTX
Grand Central Dispatch
PDF
Blocks & GCD
KEY
Blocks & Grand Central Dispatch
KEY
Grand Central Dispatch Design Patterns
PDF
Dragoncraft Architectural Overview
PDF
Philly Tech Week Introduction to NodeJS
Tech Talk #4 : Multi - threading and GCD ( grand central dispatch ) in iOS - ...
GCD and OperationQueue.
Grand Central Dispatch
Blocks & GCD
Blocks & Grand Central Dispatch
Grand Central Dispatch Design Patterns
Dragoncraft Architectural Overview
Philly Tech Week Introduction to NodeJS

What's hot (20)

PDF
JCConf 2020 - New Java Features Released in 2020
PPTX
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
PDF
06 - Qt Communication
PPTX
Building High-Performance Language Implementations With Low Effort
PPTX
Jafka guide
PPTX
Optimizing Communicating Event-Loop Languages with Truffle
PDF
Non-blocking synchronization — what is it and why we (don't?) need it
PPT
Intro2 Cuda Moayad
PPT
Find bottleneck and tuning in Java Application
PDF
Multithreading done right
PPTX
Scalable Web Apps
PPTX
Async await in C++
PDF
04 - Qt Data
PDF
How and Where in GLORP
PDF
Java Runtime: повседневные обязанности JVM
PDF
Advanced Scenegraph Rendering Pipeline
PPTX
Introduction to node.js
KEY
Concurrent Programming Using the Disruptor
PPT
Reactive programming with examples
PDF
Java Concurrency Idioms
JCConf 2020 - New Java Features Released in 2020
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
06 - Qt Communication
Building High-Performance Language Implementations With Low Effort
Jafka guide
Optimizing Communicating Event-Loop Languages with Truffle
Non-blocking synchronization — what is it and why we (don't?) need it
Intro2 Cuda Moayad
Find bottleneck and tuning in Java Application
Multithreading done right
Scalable Web Apps
Async await in C++
04 - Qt Data
How and Where in GLORP
Java Runtime: повседневные обязанности JVM
Advanced Scenegraph Rendering Pipeline
Introduction to node.js
Concurrent Programming Using the Disruptor
Reactive programming with examples
Java Concurrency Idioms
Ad

Viewers also liked (6)

PPTX
Programação Assíncrona com C# 5
PDF
TDC 2012 Goiânia: Trilha .NET - Novidades do .NET Framework 4.5
PDF
IAsyncResult Pattern ou Asynchronous Programming Model (APM)
PDF
Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DE...
PDF
Objective-C Blocks and Grand Central Dispatch
PDF
Programação assíncrona com C#
Programação Assíncrona com C# 5
TDC 2012 Goiânia: Trilha .NET - Novidades do .NET Framework 4.5
IAsyncResult Pattern ou Asynchronous Programming Model (APM)
Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DE...
Objective-C Blocks and Grand Central Dispatch
Programação assíncrona com C#
Ad

Similar to Grand Central Dispatch - iOS Conf SG 2015 (20)

PDF
Let Grunt do the work, focus on the fun!
ZIP
Building Web Apps Sanely - EclipseCon 2010
PDF
GCD in Action
ZIP
Google Developer Fest 2010
PDF
Gitlab ci e kubernetes, build test and deploy your projects like a pro
PDF
[HKOSCon x COSCUP 2020][20200801][Ansible: From VM to Kubernetes]
PDF
Dissecting Real-World Database Performance Dilemmas
PDF
Scala.IO 2024: Mill builds in Scala 3, a migration story
PPTX
Optimization and fault tolerance in distributed transaction with Node.JS Grap...
PDF
Improving Apache Spark Downscaling
PDF
In the Brain of Hans Dockter: Gradle
PDF
Coscup x ruby conf tw 2021 google cloud buildpacks 剖析與實踐
PDF
Why Grails
PDF
Why Grails?
PDF
Advanced Node.JS Meetup
PDF
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
KEY
JBoss World 2010
PDF
A New Chapter of Data Processing with CDK
PDF
Android Developer Days: Increasing performance of big arrays processing on An...
Let Grunt do the work, focus on the fun!
Building Web Apps Sanely - EclipseCon 2010
GCD in Action
Google Developer Fest 2010
Gitlab ci e kubernetes, build test and deploy your projects like a pro
[HKOSCon x COSCUP 2020][20200801][Ansible: From VM to Kubernetes]
Dissecting Real-World Database Performance Dilemmas
Scala.IO 2024: Mill builds in Scala 3, a migration story
Optimization and fault tolerance in distributed transaction with Node.JS Grap...
Improving Apache Spark Downscaling
In the Brain of Hans Dockter: Gradle
Coscup x ruby conf tw 2021 google cloud buildpacks 剖析與實踐
Why Grails
Why Grails?
Advanced Node.JS Meetup
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
JBoss World 2010
A New Chapter of Data Processing with CDK
Android Developer Days: Increasing performance of big arrays processing on An...

Recently uploaded (20)

PDF
Digital Systems & Binary Numbers (comprehensive )
PPTX
Why Generative AI is the Future of Content, Code & Creativity?
PPTX
Monitoring Stack: Grafana, Loki & Promtail
PDF
Designing Intelligence for the Shop Floor.pdf
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PDF
Types of Token_ From Utility to Security.pdf
DOCX
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
PPTX
chapter 5 systemdesign2008.pptx for cimputer science students
PPTX
Computer Software and OS of computer science of grade 11.pptx
PDF
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
PDF
Time Tracking Features That Teams and Organizations Actually Need
PDF
Complete Guide to Website Development in Malaysia for SMEs
PPTX
Trending Python Topics for Data Visualization in 2025
PDF
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
PDF
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
PPTX
Introduction to Windows Operating System
PDF
DuckDuckGo Private Browser Premium APK for Android Crack Latest 2025
PPTX
"Secure File Sharing Solutions on AWS".pptx
PDF
MCP Security Tutorial - Beginner to Advanced
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
Digital Systems & Binary Numbers (comprehensive )
Why Generative AI is the Future of Content, Code & Creativity?
Monitoring Stack: Grafana, Loki & Promtail
Designing Intelligence for the Shop Floor.pdf
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
Types of Token_ From Utility to Security.pdf
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
chapter 5 systemdesign2008.pptx for cimputer science students
Computer Software and OS of computer science of grade 11.pptx
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
Time Tracking Features That Teams and Organizations Actually Need
Complete Guide to Website Development in Malaysia for SMEs
Trending Python Topics for Data Visualization in 2025
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
Ableton Live Suite for MacOS Crack Full Download (Latest 2025)
Introduction to Windows Operating System
DuckDuckGo Private Browser Premium APK for Android Crack Latest 2025
"Secure File Sharing Solutions on AWS".pptx
MCP Security Tutorial - Beginner to Advanced
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency

Grand Central Dispatch - iOS Conf SG 2015

  • 1. Grand Central Dispatch Ben Asher basher@yelp.com benasher44 on Github and Twitter
  • 2. Yelp’s Mission: Connecting people with great local businesses. 2
  • 3. Yelp Stats: As of Q2 2015 83M 3268%83M 3
  • 4. A Responsive App - Responsive UI - Don’t make the user wait 4
  • 5. GCD - Getting Started Basics of blocks in Objective-C 5 - Segment of code - Passed around as parameters - Stored in variables - Called like C functions () ^{ // Some code };
  • 6. What is GCD about? “…technology that you use to manage the execution of tasks in your app…” - Apple Docs 6
  • 7. - C API (mostly) - Open source! - Task = ^{} GCD - Intro 7
  • 8. - Schedule tasks - dispatch_queue - Synchronize tasks - dispatch_group - Serialize asynchronous tasks - dispatch_suspend and dispatch_resume GCD Techniques 8
  • 10. GCD - Scheduling Tasks with Queues Queues Serial Concurrent 10
  • 11. GCD - Scheduling Tasks with Queues Queues ^{1}^{2} ^{1}^{2}^{3} ^{3} 11
  • 12. dispatch_queue_t dispatch_queue_create( const char *label, dispatch_queue_attr_t attr ); dispatch_queue_create(“q”, DISPATCH_QUEUE_SERIAL); dispatch_queue_create(“q”, DISPATCH_QUEUE_CONCURRENT); GCD - Scheduling Tasks with Queues 12
  • 13. Quality of Service Class - Urgency of queued tasks - Relative priority GCD - Scheduling Tasks with Queues iOS 8+ QOS_CLASS_USER_INTERACTIVE QOS_CLASS_USER_INITIATED QOS_CLASS_DEFAULT QOS_CLASS_UTILITY QOS_CLASS_BACKGROUND 13
  • 14. GCD - Scheduling Tasks with Queues iOS 8+ QOS_CLASS_USER_INTERACTIVE QOS_CLASS_USER_INITIATED QOS_CLASS_DEFAULT QOS_CLASS_UTILITY QOS_CLASS_BACKGROUND 14 dispatch_queue_attr_make_with_qos_class(DISPATCH_QUEUE_SERIAL, QOS_CLASS_UTILITY, 0); QOS_CLASS_USER_INITIATED QOS_CLASS_UTILITY
  • 15. - 5 Global Queues - 1 per QOS class - Concurrent, background thread GCD - Scheduling Tasks with Queues dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0); 15
  • 16. Queues can target other queues - (a) dispatch_queue_create(“q”, DISPATCH_QUEUE_SERIAL); GCD - Scheduling Tasks with Queues ^{2}^{3} ^{1} (a) 16 (b) - (b) Global QOS_CLASS_DEFAULT
  • 17. GCD - Scheduling Tasks with Queues ^{3} ^{2} ^{1} dispatch_set_target_queue(someQ, targetQ); (a) (b) 17
  • 18. GCD - Scheduling Tasks with Queues 18 QOS_CLASS_UTILITY QOS_CLASS_USER_INITIATED
  • 19. GCD - Scheduling Tasks with Queues Task - dispatch_block_t b = ^{}; Schedule a task in GCD - dispatch_sync(queue, ^{}) // Blocking - dispatch_async(queue, ^{}) // Non blocking 19
  • 20. GCD - Scheduling Tasks with Queues - Special 6th global queue - main queue - dispatch_get_main_queue() - Executes blocks on the main thread 20
  • 21. GCD - Scheduling Tasks with Queues Common Pattern dispatch_async(dispatch_get_global_queue(QOS_CLASS_DEFAULT), ^{ // do some expensive work dispatch_async(dispatch_get_main_queue(), ^{ // show user the work i did }); }); 21
  • 24. GCD - Synchronizing Tasks Problem - User generated video - 2 tasks: - Crop video - Generate thumbnails for keyframe slider 24
  • 25. GCD - Synchronizing Tasks Potential Solution - BOOL Flags - isVideoProccessed - areSliderImagesGenerated - (void)hideLoadingIfPossible { if (self.isVideoProcessed && self.areSliderImagesGenerated) { // Hide the loading spinner } } 25
  • 26. GCD - Synchronizing Tasks Potential Solution - BOOL Flags - (void)hideLoadingIfPossible { if (self.isVideoProcessed && self.areSliderImagesGenerated && self.isAudioProcessed && self.isUserReadyToSeeThis self.areYouSureUserIsReady) { // Hide the loading spinner } } 26
  • 27. Better Solution - Dispatch Groups dispatch_group_t - dispatch_group_create(); - Creates a new empty group - dispatch_group_enter(group); - Increments the number of tasks in group - dispatch_group_leave(group); - Decrements the number of tasks in group GCD - Synchronizing Tasks 27
  • 28. Potential solution - Dispatch Groups dispatch_group_t group = dispatch_group_create(); // For each task: // call dispatch_group_enter(group) on start // call dispatch_group_leave on tasks completion // Call wait to block until task count is 0 dispatch_group_wait(group, DISPATCH_TIME_FOREVER); GCD - Synchronizing Tasks 28
  • 29. Potential solution - Dispatch Groups dispatch_group_t group = dispatch_group_create(); // For each task: // call dispatch_group_enter(group) on start // call dispatch_group_leave on tasks completion dispatch_async(someConcurrentQueue, ^{ // Call wait to block until task count is 0 dispatch_group_wait(group, DISPATCH_TIME_FOREVER); }); GCD - Synchronizing Tasks 29
  • 30. GCD - Synchronizing Tasks Optimal Solution - dispatch_group_notify(group, queue, block); - Read “When there are no tasks left associated with this group, notify by enqueueing this block onto this queue” 30
  • 33. Sync Task - Easily fits into a block - Blocks until the task is done Async Task - Task happens in another thread/process - Starting this task returns immediately GCD - Serialize Async Tasks 33
  • 34. Problem - Animations GCD - Serialize Async Tasks 34
  • 35. GCD - Serialize Async Tasks Problem - Animations [UIView animateWithDuration:1.0 animations:^{ // Rotate 90 degrees } completion:^(BOOL finished) { [UIView animateWithDuration:0.5 animations:^{ // Move down the screen 100pt } completion:NULL]; }]; 35
  • 37. GCD - Caveats Cleanup is hard - if a dispatch_group_t is deallocated with a non- zero task count, it will throw an exception - dispatch_async “…The queue is retained by the system until the block has run to completion…” - Apple Docs 37
  • 38. Tools in the Toolbelt GCD - Small synchronous tasks - Simple asynchronous tasks NSOperation and NSOperationQueue - Complex asynchronous tasks - Cancel support 38
  • 39. What else can I do with GCD? - Efficient reader/writer schemes - dispatch_barrier - Read and write data efficiently - dispatch_io (disk) and dispatch_data (memory) - Respond to low-level system objects - dispatch_source 39
  • 40. Resources GCD Source - https://libdispatch.macosforge.org/trac/browser/trunk GCD Documentation - https://developer.apple. com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/ Demo App - https://github.com/benasher44/SGConf2015Demo 40