SlideShare a Scribd company logo
1 of 40
Download to read offline
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

What's hot

JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020JCConf 2020 - New Java Features Released in 2020
JCConf 2020 - New Java Features Released in 2020Joseph Kuo
 
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...
Zero-Overhead Metaprogramming: Reflection and Metaobject Protocols Fast and w...Stefan Marr
 
06 - Qt Communication
06 - Qt Communication06 - Qt Communication
06 - Qt CommunicationAndreas Jakl
 
Building High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortBuilding High-Performance Language Implementations With Low Effort
Building High-Performance Language Implementations With Low EffortStefan Marr
 
Jafka guide
Jafka guideJafka guide
Jafka guideAdy Liu
 
Optimizing Communicating Event-Loop Languages with Truffle
Optimizing Communicating Event-Loop Languages with TruffleOptimizing Communicating Event-Loop Languages with Truffle
Optimizing Communicating Event-Loop Languages with TruffleStefan Marr
 
Non-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itNon-blocking synchronization — what is it and why we (don't?) need it
Non-blocking synchronization — what is it and why we (don't?) need itAlexey Fyodorov
 
Intro2 Cuda Moayad
Intro2 Cuda MoayadIntro2 Cuda Moayad
Intro2 Cuda MoayadMoayadhn
 
Find bottleneck and tuning in Java Application
Find bottleneck and tuning in Java ApplicationFind bottleneck and tuning in Java Application
Find bottleneck and tuning in Java Applicationguest1f2740
 
Multithreading done right
Multithreading done rightMultithreading done right
Multithreading done rightPlatonov Sergey
 
Async await in C++
Async await in C++Async await in C++
Async await in C++cppfrug
 
How and Where in GLORP
How and Where in GLORPHow and Where in GLORP
How and Where in GLORPESUG
 
Java Runtime: повседневные обязанности JVM
Java Runtime: повседневные обязанности JVMJava Runtime: повседневные обязанности JVM
Java Runtime: повседневные обязанности JVModnoklassniki.ru
 
Advanced Scenegraph Rendering Pipeline
Advanced Scenegraph Rendering PipelineAdvanced Scenegraph Rendering Pipeline
Advanced Scenegraph Rendering PipelineNarann29
 
Introduction to node.js
Introduction to node.jsIntroduction to node.js
Introduction to node.jsDinesh U
 
Concurrent Programming Using the Disruptor
Concurrent Programming Using the DisruptorConcurrent Programming Using the Disruptor
Concurrent Programming Using the DisruptorTrisha Gee
 
Reactive programming with examples
Reactive programming with examplesReactive programming with examples
Reactive programming with examplesPeter Lawrey
 
Java Concurrency Idioms
Java Concurrency IdiomsJava Concurrency Idioms
Java Concurrency IdiomsAlex Miller
 

What's hot (20)

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

Viewers also liked

Programação Assíncrona com C# 5
Programação Assíncrona com C# 5Programação Assíncrona com C# 5
Programação Assíncrona com C# 5iMasters
 
TDC 2012 Goiânia: Trilha .NET - Novidades do .NET Framework 4.5
TDC 2012 Goiânia: Trilha .NET - Novidades do .NET Framework 4.5TDC 2012 Goiânia: Trilha .NET - Novidades do .NET Framework 4.5
TDC 2012 Goiânia: Trilha .NET - Novidades do .NET Framework 4.5Rogério Moraes de Carvalho
 
IAsyncResult Pattern ou Asynchronous Programming Model (APM)
IAsyncResult Pattern ou Asynchronous Programming Model (APM)IAsyncResult Pattern ou Asynchronous Programming Model (APM)
IAsyncResult Pattern ou Asynchronous Programming Model (APM)Rogério Moraes de Carvalho
 
Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DE...
Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DE...Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DE...
Programação assíncrona com C# 5 no Visual Studio 2013 [MVP ShowCast 2013 - DE...Rogério Moraes de Carvalho
 
Objective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchObjective-C Blocks and Grand Central Dispatch
Objective-C Blocks and Grand Central DispatchMatteo Battaglio
 
Programação assíncrona com C#
Programação assíncrona com C#Programação assíncrona com C#
Programação assíncrona com C#Giovanni Bassi
 

Viewers also liked (6)

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

Similar to Grand Central Dispatch - iOS Conf SG 2015

Let Grunt do the work, focus on the fun!
Let Grunt do the work, focus on the fun!Let Grunt do the work, focus on the fun!
Let Grunt do the work, focus on the fun!Dirk Ginader
 
Building Web Apps Sanely - EclipseCon 2010
Building Web Apps Sanely - EclipseCon 2010Building Web Apps Sanely - EclipseCon 2010
Building Web Apps Sanely - EclipseCon 2010Chris Ramsdale
 
Google Developer Fest 2010
Google Developer Fest 2010Google Developer Fest 2010
Google Developer Fest 2010Chris Ramsdale
 
Gitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a proGitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a prosparkfabrik
 
[HKOSCon x COSCUP 2020][20200801][Ansible: From VM to Kubernetes]
[HKOSCon x COSCUP 2020][20200801][Ansible: From VM to Kubernetes][HKOSCon x COSCUP 2020][20200801][Ansible: From VM to Kubernetes]
[HKOSCon x COSCUP 2020][20200801][Ansible: From VM to Kubernetes]Wong Hoi Sing Edison
 
Dissecting Real-World Database Performance Dilemmas
Dissecting Real-World Database Performance DilemmasDissecting Real-World Database Performance Dilemmas
Dissecting Real-World Database Performance DilemmasScyllaDB
 
Improving Apache Spark Downscaling
 Improving Apache Spark Downscaling Improving Apache Spark Downscaling
Improving Apache Spark DownscalingDatabricks
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleSkills Matter
 
Coscup x ruby conf tw 2021 google cloud buildpacks 剖析與實踐
Coscup x ruby conf tw 2021  google cloud buildpacks 剖析與實踐Coscup x ruby conf tw 2021  google cloud buildpacks 剖析與實踐
Coscup x ruby conf tw 2021 google cloud buildpacks 剖析與實踐KAI CHU CHUNG
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS MeetupLINAGORA
 
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Rajmahendra Hegde
 
A New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDKA New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDKShu-Jeng Hsieh
 
Android Developer Days: Increasing performance of big arrays processing on An...
Android Developer Days: Increasing performance of big arrays processing on An...Android Developer Days: Increasing performance of big arrays processing on An...
Android Developer Days: Increasing performance of big arrays processing on An...Stanfy
 
Get Grulping with JavaScript Task Runners (Matt Gifford)
Get Grulping with JavaScript Task Runners (Matt Gifford)Get Grulping with JavaScript Task Runners (Matt Gifford)
Get Grulping with JavaScript Task Runners (Matt Gifford)Future Insights
 

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

Concurrency in Swift
Concurrency in SwiftConcurrency in Swift
Concurrency in Swift
 
Let Grunt do the work, focus on the fun!
Let Grunt do the work, focus on the fun!Let Grunt do the work, focus on the fun!
Let Grunt do the work, focus on the fun!
 
Building Web Apps Sanely - EclipseCon 2010
Building Web Apps Sanely - EclipseCon 2010Building Web Apps Sanely - EclipseCon 2010
Building Web Apps Sanely - EclipseCon 2010
 
GCD in Action
GCD in ActionGCD in Action
GCD in Action
 
Google Developer Fest 2010
Google Developer Fest 2010Google Developer Fest 2010
Google Developer Fest 2010
 
Modern c++
Modern c++Modern c++
Modern c++
 
Gitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a proGitlab ci e kubernetes, build test and deploy your projects like a pro
Gitlab ci e kubernetes, build test and deploy your projects like a pro
 
[HKOSCon x COSCUP 2020][20200801][Ansible: From VM to Kubernetes]
[HKOSCon x COSCUP 2020][20200801][Ansible: From VM to Kubernetes][HKOSCon x COSCUP 2020][20200801][Ansible: From VM to Kubernetes]
[HKOSCon x COSCUP 2020][20200801][Ansible: From VM to Kubernetes]
 
Dissecting Real-World Database Performance Dilemmas
Dissecting Real-World Database Performance DilemmasDissecting Real-World Database Performance Dilemmas
Dissecting Real-World Database Performance Dilemmas
 
Improving Apache Spark Downscaling
 Improving Apache Spark Downscaling Improving Apache Spark Downscaling
Improving Apache Spark Downscaling
 
In the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: GradleIn the Brain of Hans Dockter: Gradle
In the Brain of Hans Dockter: Gradle
 
Coscup x ruby conf tw 2021 google cloud buildpacks 剖析與實踐
Coscup x ruby conf tw 2021  google cloud buildpacks 剖析與實踐Coscup x ruby conf tw 2021  google cloud buildpacks 剖析與實踐
Coscup x ruby conf tw 2021 google cloud buildpacks 剖析與實踐
 
Why Grails?
Why Grails?Why Grails?
Why Grails?
 
Why Grails
Why GrailsWhy Grails
Why Grails
 
Advanced Node.JS Meetup
Advanced Node.JS MeetupAdvanced Node.JS Meetup
Advanced Node.JS Meetup
 
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012Gradle build tool that rocks with DSL JavaOne India 4th May 2012
Gradle build tool that rocks with DSL JavaOne India 4th May 2012
 
JBoss World 2010
JBoss World 2010JBoss World 2010
JBoss World 2010
 
A New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDKA New Chapter of Data Processing with CDK
A New Chapter of Data Processing with CDK
 
Android Developer Days: Increasing performance of big arrays processing on An...
Android Developer Days: Increasing performance of big arrays processing on An...Android Developer Days: Increasing performance of big arrays processing on An...
Android Developer Days: Increasing performance of big arrays processing on An...
 
Get Grulping with JavaScript Task Runners (Matt Gifford)
Get Grulping with JavaScript Task Runners (Matt Gifford)Get Grulping with JavaScript Task Runners (Matt Gifford)
Get Grulping with JavaScript Task Runners (Matt Gifford)
 

Recently uploaded

Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identityteam-WIBU
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Rob Geurden
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfDrew Moseley
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Angel Borroy López
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Velvetech LLC
 

Recently uploaded (20)

Post Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on IdentityPost Quantum Cryptography – The Impact on Identity
Post Quantum Cryptography – The Impact on Identity
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva2.pdf Ejercicios de programación competitiva
2.pdf Ejercicios de programación competitiva
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...Simplifying Microservices & Apps - The art of effortless development - Meetup...
Simplifying Microservices & Apps - The art of effortless development - Meetup...
 
Comparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdfComparing Linux OS Image Update Models - EOSS 2024.pdf
Comparing Linux OS Image Update Models - EOSS 2024.pdf
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
Alfresco TTL#157 - Troubleshooting Made Easy: Deciphering Alfresco mTLS Confi...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...Software Project Health Check: Best Practices and Techniques for Your Product...
Software Project Health Check: Best Practices and Techniques for Your Product...
 

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