SlideShare a Scribd company logo
34 AVENUE DE L’OPÉRA > 75002 PARIS > FRANCE > WWW.OCTO.COM
08/03/2018
ASYNCHRONOUS SWIFT
Jordhan Leoture
TABLE OF CONTENT
01
02
03
04
> PARALLELISM & CONCURRENCY
> FAIR LOCK & UNFAIR LOCK
> DISPATCHQUEUE
> FUTURE & PROMISE
2
01 PARALLELISM & CONCURRENCY
PARALLELISM & CONCURRENCY
PARALLELISM
A problem is solved by multiple processors
CONCURRENCY
Many problems are solved by one processor
4
PARALLELISM & CONCURRENCY
Grand Central Dispatch
5
• Reduces memory for storing thread stacks
• Reduces code related to thread
management
• Simplifies code
PARALLELISM & CONCURRENCY
Parallelism - Example
6
PARALLELISM & CONCURRENCY
Parallelism - Example
6
PARALLELISM & CONCURRENCY
Parallelism with GCD
7
DispatchQueue.concurrentPerform(16) { i in /* iteration */ }
PARALLELISM & CONCURRENCY
Parallelism with GCD
8
DispatchQueue.concurrentPerform(16) { i in /* iteration */ }
UI Rendering
PARALLELISM & CONCURRENCY
Parallelism with GCD
9
DispatchQueue.concurrentPerform(1000) { i in /* iteration */ }
UI Rendering
PARALLELISM & CONCURRENCY
Concurrency - Example
10
Task #1
#3
#4
#2
PARALLELISM & CONCURRENCY
Concurrency - Example
11
CONTEXT SWITCH
PARALLELISM & CONCURRENCY
Concurrency - Example
12
CONTEXT SWITCH
• Save the context of the current thread
• Find the context of the next thread
• Reload the context of the next thread
• Resume the next thread
PARALLELISM & CONCURRENCY
Concurrency - Example
13
The OS chooses the next thread
• A higher priority thread needs the CPU
• The current thread finishes its work
• The current thread is waiting for a resource
• The time of the current thread has expired
PARALLELISM & CONCURRENCY
Concurrency - Example
14
Other process
PARALLELISM & CONCURRENCY
Recurring problems
15
• Frequently block threads for resource access
• Many context switch between independent operations
02 FAIR LOCK & UNFAIR LOCK
FAIR LOCK & UNFAIR LOCK
17
FAIR LOCK & UNFAIR LOCK
Fair lock
18
owned reserved owned reserved
FAIR LOCK & UNFAIR LOCK
Unfair lock
19
owned waiters owned waiters
FAIR LOCK & UNFAIR LOCK
FAIR LOCK
No waiter starvation but many context switches
UNFAIR LOCK
Subject to waiter starvation but reduced context switches
20
FAIR LOCK & UNFAIR LOCK
21
FAIR LOCK
(dispatch_semaphore)
UNFAIR LOCK
(os_unfair_lock)
TIME BY LOCK LONG SHORT
# LOCK BY THREAD FEW MANY
# THREAD NEED THE
LOCK
MANY FEW
FAIR LOCK & UNFAIR LOCK
Recurring problems
22
• Frequently block threads for resource access
• Many context switch between independent operations
03 DISPATCHQUEUE
DISPATCHQUEUE
• Perform tasks asynchronously and concurrently
• FIFO
• Thread-safe
• Serial or concurrent
24
Good to know
DISPATCHQUEUE
25
Quality of Service Classes
User-interactive Virtually instantaneous
User-initiated Nearly instantaneous
Default No information
Utility Seconds or few minutes
Background Minutes or hours
Unspecified Legacy APIs
High
Low
DISPATCHQUEUE
26
Asynchronous
queue
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.async { /* block2 */ }
queue.async { /* block3 */ }
DISPATCHQUEUE
26
Asynchronous
queue Block1
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.async { /* block2 */ }
queue.async { /* block3 */ }
DISPATCHQUEUE
26
Asynchronous
queue Block1
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.async { /* block2 */ }
queue.async { /* block3 */ }
Block2
DISPATCHQUEUE
26
Asynchronous
queue Block1
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.async { /* block2 */ }
queue.async { /* block3 */ }
Block2 Block3
DISPATCHQUEUE
26
Asynchronous
queue Block1
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.async { /* block2 */ }
queue.async { /* block3 */ }
Block2 Block3
DISPATCHQUEUE
26
Asynchronous
queue
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.async { /* block2 */ }
queue.async { /* block3 */ }
Block2 Block3
DISPATCHQUEUE
26
Asynchronous
queue
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.async { /* block2 */ }
queue.async { /* block3 */ }
Block3
DISPATCHQUEUE
26
Asynchronous
queue
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.async { /* block2 */ }
queue.async { /* block3 */ }
DISPATCHQUEUE
27
Synchronous
queue
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.sync { /* block2 */ } // sync is a fair lock 😊
queue.async { /* block3 */ }
DISPATCHQUEUE
27
Synchronous
queue Block1
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.sync { /* block2 */ } // sync is a fair lock 😊
queue.async { /* block3 */ }
DISPATCHQUEUE
27
Synchronous
queue Block1 Block2 Block3
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.sync { /* block2 */ } // sync is a fair lock 😊
queue.async { /* block3 */ }
Block2
DISPATCHQUEUE
27
Synchronous
queue Block1 Block2 Block3
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.sync { /* block2 */ } // sync is a fair lock 😊
queue.async { /* block3 */ }
Block2
DISPATCHQUEUE
27
Synchronous
queue Block2 Block3
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.sync { /* block2 */ } // sync is a fair lock 😊
queue.async { /* block3 */ }
Block2
DISPATCHQUEUE
27
Synchronous
queue
Block2 Block3
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.sync { /* block2 */ } // sync is a fair lock 😊
queue.async { /* block3 */ }
Block2
DISPATCHQUEUE
27
Synchronous
queue
Block3
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.sync { /* block2 */ } // sync is a fair lock 😊
queue.async { /* block3 */ }
DISPATCHQUEUE
27
Synchronous
queue Block3
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.sync { /* block2 */ } // sync is a fair lock 😊
queue.async { /* block3 */ }
DISPATCHQUEUE
27
Synchronous
queue
let queue = DispatchQueue(label: "serial-queue")
queue.async { /* block1 */ }
queue.sync { /* block2 */ } // sync is a fair lock 😊
queue.async { /* block3 */ }
DISPATCHQUEUE
28
Target Queue Hierarchy
queue1 1
queue2
1 A 2 B 3 C
2 3
A B C
DISPATCHQUEUE
29
Target Queue Hierarchy
queue1
queue2
let queue0 = DispatchQueue(label: "queue0")
let queue1 = DispatchQueue(label: "queue1", target: queue0)
let queue2 = DispatchQueue(label: "queue2", target: queue0)
queue0
3
C
2
BA
1
DISPATCHQUEUE
29
Target Queue Hierarchy
queue1
queue2
let queue0 = DispatchQueue(label: "queue0")
let queue1 = DispatchQueue(label: "queue1", target: queue0)
let queue2 = DispatchQueue(label: "queue2", target: queue0)
queue0 3C2BA1
DISPATCHQUEUE
30
Target Queue Hierarchy
let queue0 = DispatchQueue(label: "queue0")
let queue1 = DispatchQueue(label: "queue1", target: queue0)
let queue2 = DispatchQueue(label: "queue2", target: queue0)
queue0 BA1 3C2
1 A B 2 C 3
DISPATCHQUEUE
Recurring problems
31
• Frequently block threads for resource access
• Many context switch between independent operations
04 FUTURE & PROMISE
FUTURE & PROMISE
FUTURE
Wrap a value that may not exist yet
Read-Only
PROMISE
Provide an associated future
Read-Write(Once)
33
FUTURE & PROMISE
Example
34
let promise = Promise<Int>()
let future = promise.future
FUTURE & PROMISE
Example
35
let promise = Promise<Int>()
let future = promise.future
queue1.async {
future.then { i in /* success */ }
.catch { error in /* failure */ }
}
FUTURE & PROMISE
Example
36
let promise = Promise<Int>()
let future = promise.future
queue1.async {
future.then { i in /* success */ }
.catch { error in /* failure */ }
}
queue2.async {
promise.resolve { 1 }
}
FUTURE & PROMISE
Example
37
service.call(request: "…") { result in
switch result {
case let .success(data):
service.call(request: "…") { result in
switch result {…}
/* finally do something */
}
case let .failure(error): /* failure */
}
/* finally do something */
}
FUTURE & PROMISE
Example
38
service.call(request: "…") { result in
switch result {
case let .success(data):
service.call(request: "…") { result in
switch result {…}
/* finally do something */
}
case let .failure(error): /* failure */
}
/* finally do something */
}
• Is the first completion on the same Thread
that the first service.call ?
• Is the second service.call on the same Thread
that the first completion ?
• Is the second completion on the same Thread
that the second service.call ?
FUTURE & PROMISE
Example
39
service.call(request: "…")
.then(qos: .utility) { data in service.call(request: "…") }
.then(qos: .userInteractive) { data in /* success */ }
.catch(qos: .userInteractive) { error in /* failure */ }
.finally(qos: .background) { /* do something */ }
FUTURE & PROMISE
Example
40
service.call(request: "…")
.then(qos: .utility) { data in service.call(request: "…") }
.then(qos: .userInteractive) { data in /* success */ }
.catch(qos: .userInteractive) { error in /* failure */ }
.finally(qos: .background) { /* do something */ }
internalQueue thencallthen finallycatch
POD IN PROGRESS
41
https://cocoapods.org/pods/AsynchronousSwift
Asynchronous swift

More Related Content

What's hot

What's hot (11)

Powerpoint on verb aimer
Powerpoint  on verb aimerPowerpoint  on verb aimer
Powerpoint on verb aimer
 
1 the five senses
1 the five senses1 the five senses
1 the five senses
 
Parts of-speech-1222899793596097-8
Parts of-speech-1222899793596097-8Parts of-speech-1222899793596097-8
Parts of-speech-1222899793596097-8
 
Cartoon characters
Cartoon charactersCartoon characters
Cartoon characters
 
생산성을 높여주는 iOS 개발 방법들.pdf
생산성을 높여주는 iOS 개발 방법들.pdf생산성을 높여주는 iOS 개발 방법들.pdf
생산성을 높여주는 iOS 개발 방법들.pdf
 
Verbs being
Verbs beingVerbs being
Verbs being
 
Word Families
Word FamiliesWord Families
Word Families
 
ACTIVE AND PASSIVE VOICE
 ACTIVE AND PASSIVE VOICE ACTIVE AND PASSIVE VOICE
ACTIVE AND PASSIVE VOICE
 
Short Vowel Sounds Power Point
Short Vowel Sounds Power PointShort Vowel Sounds Power Point
Short Vowel Sounds Power Point
 
20220716_만들면서 느껴보는 POP
20220716_만들면서 느껴보는 POP20220716_만들면서 느껴보는 POP
20220716_만들면서 느껴보는 POP
 
Verbs Action
Verbs ActionVerbs Action
Verbs Action
 

Similar to Asynchronous swift

Profiling JavaScript Performance
Profiling JavaScript PerformanceProfiling JavaScript Performance
Profiling JavaScript Performance
FITC
 

Similar to Asynchronous swift (20)

Checking Oracle VM VirtualBox. Part 1
Checking Oracle VM VirtualBox. Part 1Checking Oracle VM VirtualBox. Part 1
Checking Oracle VM VirtualBox. Part 1
 
VLSI lab manual
VLSI lab manualVLSI lab manual
VLSI lab manual
 
Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)Counter Wars (JEEConf 2016)
Counter Wars (JEEConf 2016)
 
Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !Async Debugging A Practical Guide to survive !
Async Debugging A Practical Guide to survive !
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Taming AEM deployments
Taming AEM deploymentsTaming AEM deployments
Taming AEM deployments
 
Curator intro
Curator introCurator intro
Curator intro
 
Blocks & GCD
Blocks & GCDBlocks & GCD
Blocks & GCD
 
Endevor api an introduction to the endevor application programming interface
Endevor api   an introduction to the endevor application programming interface Endevor api   an introduction to the endevor application programming interface
Endevor api an introduction to the endevor application programming interface
 
Profiling JavaScript Performance
Profiling JavaScript PerformanceProfiling JavaScript Performance
Profiling JavaScript Performance
 
Fault Tolerance in a High Volume, Distributed System
Fault Tolerance in a  High Volume, Distributed SystemFault Tolerance in a  High Volume, Distributed System
Fault Tolerance in a High Volume, Distributed System
 
无锁编程
无锁编程无锁编程
无锁编程
 
play framework async with scala
play framework async with scalaplay framework async with scala
play framework async with scala
 
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
Analysis of Haiku Operating System (BeOS Family) by PVS-Studio. Part 2
 
The State of Lightweight Threads for the JVM
The State of Lightweight Threads for the JVMThe State of Lightweight Threads for the JVM
The State of Lightweight Threads for the JVM
 
002 hbase clientapi
002 hbase clientapi002 hbase clientapi
002 hbase clientapi
 
Async Debugging - A Practical Guide to survive !
Async Debugging - A Practical Guide to survive !Async Debugging - A Practical Guide to survive !
Async Debugging - A Practical Guide to survive !
 
Oracle Database In-Memory Option in Action
Oracle Database In-Memory Option in ActionOracle Database In-Memory Option in Action
Oracle Database In-Memory Option in Action
 
In Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry OsborneIn Memory Database In Action by Tanel Poder and Kerry Osborne
In Memory Database In Action by Tanel Poder and Kerry Osborne
 
Asterisk: PVS-Studio Takes Up Telephony
Asterisk: PVS-Studio Takes Up TelephonyAsterisk: PVS-Studio Takes Up Telephony
Asterisk: PVS-Studio Takes Up Telephony
 

More from CocoaHeads France

More from CocoaHeads France (20)

Mutation testing for a safer Future
Mutation testing for a safer FutureMutation testing for a safer Future
Mutation testing for a safer Future
 
iOS App Group for Debugging
iOS App Group for DebuggingiOS App Group for Debugging
iOS App Group for Debugging
 
Visual accessibility in iOS11
Visual accessibility in iOS11Visual accessibility in iOS11
Visual accessibility in iOS11
 
My script - One year of CocoaHeads
My script - One year of CocoaHeadsMy script - One year of CocoaHeads
My script - One year of CocoaHeads
 
Ui testing dealing with push notifications
Ui testing dealing with push notificationsUi testing dealing with push notifications
Ui testing dealing with push notifications
 
CONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANECONTINUOUS DELIVERY WITH FASTLANE
CONTINUOUS DELIVERY WITH FASTLANE
 
L'intégration continue avec Bitrise
L'intégration continue avec BitriseL'intégration continue avec Bitrise
L'intégration continue avec Bitrise
 
Super combinators
Super combinatorsSuper combinators
Super combinators
 
Design like a developer
Design like a developerDesign like a developer
Design like a developer
 
Handle the error
Handle the errorHandle the error
Handle the error
 
Quoi de neuf dans iOS 10.3
Quoi de neuf dans iOS 10.3Quoi de neuf dans iOS 10.3
Quoi de neuf dans iOS 10.3
 
IoT Best practices
 IoT Best practices IoT Best practices
IoT Best practices
 
SwiftyGPIO
SwiftyGPIOSwiftyGPIO
SwiftyGPIO
 
Présentation de HomeKit
Présentation de HomeKitPrésentation de HomeKit
Présentation de HomeKit
 
Programme MFI retour d'expérience
Programme MFI retour d'expérienceProgramme MFI retour d'expérience
Programme MFI retour d'expérience
 
How to communicate with Smart things?
How to communicate with Smart things?How to communicate with Smart things?
How to communicate with Smart things?
 
Build a lego app with CocoaPods
Build a lego app with CocoaPodsBuild a lego app with CocoaPods
Build a lego app with CocoaPods
 
Let's migrate to Swift 3.0
Let's migrate to Swift 3.0Let's migrate to Swift 3.0
Let's migrate to Swift 3.0
 
Project Entourage
Project EntourageProject Entourage
Project Entourage
 
What's new in iOS9
What's new in iOS9What's new in iOS9
What's new in iOS9
 

Recently uploaded

JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
Max Lee
 

Recently uploaded (20)

SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
Breaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdfBreaking the Code : A Guide to WhatsApp Business API.pdf
Breaking the Code : A Guide to WhatsApp Business API.pdf
 
AI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in MichelangeloAI/ML Infra Meetup | ML explainability in Michelangelo
AI/ML Infra Meetup | ML explainability in Michelangelo
 
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with StrimziStrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
StrimziCon 2024 - Transition to Apache Kafka on Kubernetes with Strimzi
 
A Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data MigrationA Guideline to Zendesk to Re:amaze Data Migration
A Guideline to Zendesk to Re:amaze Data Migration
 
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
Abortion ^Clinic ^%[+971588192166''] Abortion Pill Al Ain (?@?) Abortion Pill...
 
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product UpdatesGraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
GraphSummit Stockholm - Neo4j - Knowledge Graphs and Product Updates
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)JustNaik Solution Deck (stage bus sector)
JustNaik Solution Deck (stage bus sector)
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
AI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning FrameworkAI/ML Infra Meetup | Perspective on Deep Learning Framework
AI/ML Infra Meetup | Perspective on Deep Learning Framework
 
iGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by SkilrockiGaming Platform & Lottery Solutions by Skilrock
iGaming Platform & Lottery Solutions by Skilrock
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
De mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FMEDe mooiste recreatieve routes ontdekken met RouteYou en FME
De mooiste recreatieve routes ontdekken met RouteYou en FME
 
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
A Python-based approach to data loading in TM1 - Using Airflow as an ETL for TM1
 
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
How Does XfilesPro Ensure Security While Sharing Documents in Salesforce?
 
GraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysisGraphAware - Transforming policing with graph-based intelligence analysis
GraphAware - Transforming policing with graph-based intelligence analysis
 
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
Facemoji Keyboard released its 2023 State of Emoji report, outlining the most...
 
Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024Secure Software Ecosystem Teqnation 2024
Secure Software Ecosystem Teqnation 2024
 
Into the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdfInto the Box 2024 - Keynote Day 2 Slides.pdf
Into the Box 2024 - Keynote Day 2 Slides.pdf
 

Asynchronous swift