PDF Concurrency by Tutorials Second Edition Multithreading in Swift With GCD and Operations Tutorial Team Download
PDF Concurrency by Tutorials Second Edition Multithreading in Swift With GCD and Operations Tutorial Team Download
com
https://textbookfull.com/product/concurrency-by-
tutorials-second-edition-multithreading-in-swift-
with-gcd-and-operations-tutorial-team/
https://textbookfull.com/product/design-patterns-by-tutorials-third-
edition-learning-design-patterns-in-swift-raywenderlich-tutorial-team/
textbookfull.com
https://textbookfull.com/product/ios-11-by-tutorials-learning-the-new-
ios-apis-with-swift-4-1st-edition-the-raywenderlich-tutorial-team/
textbookfull.com
https://textbookfull.com/product/rxswift-reactive-programming-with-
swift-third-edition-raywenderlich-tutorial-team/
textbookfull.com
https://textbookfull.com/product/ethnic-dignity-and-the-ulster-scots-
movement-in-northern-ireland-supremacy-in-peril-peter-gardner/
textbookfull.com
https://textbookfull.com/product/cyclodextrins-properties-and-
industrial-applications-1st-edition-amiri/
textbookfull.com
https://textbookfull.com/product/robot-proof-higher-education-in-the-
age-of-artificial-intelligence-joseph-e-aoun/
textbookfull.com
https://textbookfull.com/product/myth-in-indo-european-antiquity-
publications-of-the-ucsb-institute-of-religious-studies-first-edition-
larson/
textbookfull.com
https://textbookfull.com/product/storm-dragons-02-0-trapped-by-the-
dragon-1st-edition-riley-storm/
textbookfull.com
Fundamentals of Toxicologic Pathology 3rd Edition Matthew
A. Wallig Et Al.
https://textbookfull.com/product/fundamentals-of-toxicologic-
pathology-3rd-edition-matthew-a-wallig-et-al/
textbookfull.com
Concurrency by Tutorials
Concurrency by Tutorials
By Scott Grosch
Notice of Rights
All rights reserved. No part of this book or corresponding materials (such as text,
images, or source code) may be reproduced or distributed by any means without prior
written permission of the copyright owner.
Notice of Liability
This book and all corresponding materials (such as source code) are provided on an
“as is” basis, without warranty of any kind, express of implied, including but not
limited to the warranties of merchantability, fitness for a particular purpose, and
noninfringement. In no event shall the authors or copyright holders be liable for any
claim, damages or other liability, whether in action of contract, tort or otherwise,
arising from, out of or in connection with the software or the use of other dealing in
the software.
Trademarks
All trademarks and registered trademarks appearing in this book are the property of
their own respective owners.
raywenderlich.com 2
Concurrency by Tutorials
raywenderlich.com 3
Concurrency by Tutorials
raywenderlich.com 4
Concurrency by Tutorials
raywenderlich.com 5
Concurrency by Tutorials
raywenderlich.com 6
Concurrency by Tutorials
raywenderlich.com 7
A About the Cover
Our usual experience when looking at an animal is to see the creature and know,
clearly, how its body is assigned and what each of its parts does — two legs for
walking, two ears for hearing, a mouth for eating, gills for breathing, one brain for
thinking.
Everything about the starfish is in multitudes that aren't always obvious to our eye:
five–50 arms, a mouth with five jaws, a eyespot on each arm with 80–100 ocelli, a
decentralized respiratory and central nervous system, a three-ringed circulatory
system, a common “mouth” used both in consuming and excreting, and tubed “feet”
that assist with sensing, moving and breathing.
If you find yourself on the east coast of the continental Americas, especially the
Caribbean, keep an eye out for a relatively small, impossibly purple seastar with
brilliant orange edges.
raywenderlich.com 8
Concurrency by Tutorials About the Cover
Dedications
"This book is dedicated to my wife and daughter, as well as to
my parents who always made sure a good education was a
priority."
— Scott Grosch
raywenderlich.com 9
Concurrency by Tutorials About the Cover
Shai Mishali is the Final Pass Editor of this book. He's the iOS
Tech Lead for Gett, the global on-demand mobility company; as
well as an international speaker, and a highly active open-source
contributor and maintainer on several high-profile projects -
namely, the RxSwift Community and RxSwift projects. As an avid
enthusiast of hackathons, Shai took 1st place at BattleHack Tel-
Aviv 2014, BattleHack World Finals San Jose 2014, and Ford's
Developer Challenge Tel-Aviv 2015. You can find him on GitHub
and Twitter @freak4pc.
Manda Frederick is the editor of this book. She has been involved
in publishing for over 10 years through various creative,
educational, medical and technical print and digital publications,
and is thrilled to bring her experience to the raywenderlich.com
family as Managing Editor. In her free time, you can find her at the
climbing gym, backpacking in the backcountry, hanging with her
dog, working on poems, playing guitar and exploring breweries.
raywenderlich.com 10
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
Concurrency by Tutorials About the Cover
raywenderlich.com 11
A Acknowledgements
Luke Freeman for coordinating and/or creating many of the images that you see in
this book.
raywenderlich.com 12
W What You Need
• A Mac running macOS Mojave (10.14) or later. Earlier versions might work, but
they're untested.
• Xcode 11 or later. Xcode is the main development tool for iOS. While earlier
versions of Xcode should work, the examples in this book have been specifically
tested on Xcode 11 and iOS 13. You can download the latest version of Xcode from
Apple’s developer site here: apple.co/2asi58y
If you want to try things out on a physical iOS device, you’ll need a developer
account with Apple, which you can obtain for free. However, all the sample projects
in this book will work just fine in the iOS Simulator bundled with Xcode, so the paid
developer account is completely optional.
raywenderlich.com 13
L Book License
• You are allowed to use and/or modify the source code in Concurrency by Tutorials in
as many apps as you want, with no attribution required.
• You are allowed to use and/or modify all art, images and designs that are included
in Concurrency by Tutorials in as many apps as you want, but must include this
attribution line somewhere inside your app: “Artwork/images/designs: from
Concurrency by Tutorials, available at www.raywenderlich.com”.
• The source code included in Concurrency by Tutorials is for your personal use only.
You are NOT allowed to distribute or sell the source code in Concurrency by
Tutorials without prior authorization.
• This book is for your personal use only. You are NOT allowed to sell this book
without prior authorization, or distribute it to friends, coworkers or students; they
would need to purchase their own copies.
All materials provided with this book are provided on an “as is” basis, without
warranty of any kind, express or implied, including but not limited to the warranties
of merchantability, fitness for a particular purpose and noninfringement. In no event
shall the authors or copyright holders be liable for any claim, damages or other
liability, whether in an action or contract, tort or otherwise, arising from, out of or in
connection with the software or the use or other dealings in the software.
All trademarks and registered trademarks appearing in this guide are the properties
of their respective owners.
raywenderlich.com 14
B Book Source Code &
Forums
The digital edition of this book also comes with free access to any future updates we
may make to the book!
The best way to get update notifications is to sign up for our monthly newsletter.
This includes a list of the tutorials that came out on raywenderlich.com that month,
any important news like book updates or new books, and a list of our favorite iOS
development links for that month. You can sign up here:
• www.raywenderlich.com/newsletter
https://store.raywenderlich.com/products/concurrency-by-tutorials-source-code
Forums
We’ve also set up an official forum for the book at forums.raywenderlich.com. This is
a great place to ask questions about the book or to submit any errors you may find.
raywenderlich.com 15
Concurrency by Tutorials Book Source Code & Forums
Buying the digital edition version of the book also has a few extra benefits: free
updates each time we update the book, access to older versions of the book, and you
can download the digital editions from anywhere, at anytime.
• https://store.raywenderlich.com/products/concurrency-by-tutorials.
And if you purchased the print version of this book, you’re eligible to upgrade to the
digital editions at a significant discount! Simply email support@razeware.com with
your receipt for the physical copy and we’ll get you set up with the discounted digital
edition version of the book.
raywenderlich.com 16
Section I: Getting Started with
Concurrency
In this part of the book, you’re going to learn about the basics of Concurrency. You're
going to learn what it is, what kind of problems it solves, and why would you even
use it?
Further, you will learn the basic pieces of which Concurrency comprises in iOS
development: Grand Central Dispatch and Operations.
This section will provide you with the foundational knowledge regarding
Concurrency, so be sure to read through! The upcoming sections will dive much
deeper into each of these concepts individually.
Chapter 1: Introduction: Get a quick overview of what concurrency is and why you
might want to use it.
raywenderlich.com 17
1 Chapter 1: Introduction
Performance. Responsiveness. They’re not sexy tasks. When done properly, nobody is
going to thank you. When done incorrectly, app retention is going to suffer and you’ll
be dinged during your next yearly performance review.
There are a multitude of ways in which an app can be optimized for speed,
performance and overall responsiveness. This book will focus on the topic of
concurrency.
What is concurrency?
Wikipedia defines concurrency as "the decomposability property of a program,
algorithm, or problem into order-independent or partially-ordered components or
units." What this means is looking at the logic of your app to determine which pieces
can run at the same time, and possibly in a random order, yet still result in a correct
implementation of your data flow.
Moderns devices almost always have more than a single CPU, and Apple’s iPhones
have been dual core since 2011. Having more than one core means they are capable
of running more than a single task at the same time. By splitting your app into
logical "chunks" of code you enable the iOS device to run multiple parts of your
program at the same time, thus improving overall performance.
raywenderlich.com 18
Concurrency by Tutorials Chapter 1: Introduction
Scrolling through a table of images is one of the more common situations wherein
the end user will be impacted by the lack of concurrency. If you need to download an
image from the network, or perform some type of image processing before displaying
it, the scrolling will stutter and you’ll be forced to display multiple "busy" indicators
instead of the expected image.
A beneficial side effect to using concurrency is that it helps you to spend a bit more
time thinking about your app’s overall architecture. Instead of just writing massive
methods to "get the job done" you’ll find yourself naturally writing smaller, more
manageable methods that can run concurrently.
Tasks which access different resources, or read-only shared resources, can all be
accessed via different threads to allow for much faster processing.
This book will focus on the two main ways that iOS provides you with the ability to
run code concurrently. The first section on Grand Central Dispatch will cover the
common scenarios where you will find yourself being able to implement concurrency.
You’ll learn how to run tasks in the background, how to group tasks together and
how to handle restricting the number of tasks that can run at once. By the end of the
first section you’ll also have a strong grasp of the dangers of concurrency and how to
avoid them.
In the second section you’ll focus on the Operation class. Built on top of Grand
Central Dispatch, operations allow for the handling of more complex scenarios such
as reusable code to be run on a background thread, having one thread depend on
another, and even canceling an operation before it’s started or completed.
raywenderlich.com 19
Concurrency by Tutorials Chapter 1: Introduction
Most modern programming languages provide for some form of concurrency and
Swift is of course no exception. Different languages use widely different mechanisms
for handling concurrency. C# and Typescript, for example use an async/await pattern,
whereas Swift uses closures to handle what runs on another thread. Swift 5 originally
had plans to implement the more common async/await pattern but it was removed
from the specification until the next release.
raywenderlich.com 20
Visit https://textbookfull.com
now to explore a rich
collection of eBooks, textbook
and enjoy exciting offers!
2 Chapter 2: GCD &
Operations
There are two APIs that you'll use when making your app concurrent: Grand Central
Dispatch, commonly referred to as GCD, and Operations. These are neither
competing technologies nor something that you have to exclusively pick between. In
fact, Operations are built on top of GCD!
raywenderlich.com 21
Concurrency by Tutorials Chapter 2: GCD & Operations
While GCD uses threads in its implementation, you, as the developer, do not need to
worry about managing them yourself. GCD’s tasks are so lightweight to enqueue that
Apple, in its 2009 technical brief on GCD, stated that only 15 instructions are
required for implementation, whereas creating traditional threads could require
several hundred instructions.
All of the tasks that GCD manages for you are placed into GCD-managed first-in,
first-out (FIFO) queues. Each task that you submit to a queue is then executed
against a pool of threads fully managed by the system.
Note: There is no guarantee as to which thread your task will execute against.
Note: It’s important to keep in mind that, while the queues are FIFO based,
that does not ensure that tasks will finish in the order you submit them. The
FIFO procedure applies to when the task starts, not when it finishes.
raywenderlich.com 22
Concurrency by Tutorials Chapter 2: GCD & Operations
In general, you'll want to take any long-running non-UI task that you can find and
make it run asynchronously in the background. GCD makes this very simple via
closures with a few lines of code, like so:
DispatchQueue.main.async {
// Update the UI here
}
}
You'll learn all about DispatchQueue in Chapter 3, "Queues & Threads." In general,
you create a queue, submit a task to it to run asynchronously on a background
thread, and, when it’s complete, you delegate the code back to the main thread to
update the UI.
Note: While you can tell iOS that you'd like to use a concurrent queue,
remember that there is no guarantee that more than one task will run at a
time. If your iOS device is completely bogged down and your app is competing
for resources, it may only be capable of running a single task.
raywenderlich.com 23
Concurrency by Tutorials Chapter 2: GCD & Operations
In other words, a task being synchronous or not speaks to the source of the task.
Being serial or concurrent speaks to the destination of the task.
Operations
GCD is great for common tasks that need to be run a single time in the background.
When you find yourself building functionality that should be reusable — such as
image editing operations — you will likely want to encapsulate that functionality
into a class. By subclassing Operation, you can accomplish that goal!
Operation subclassing
Operations are fully-functional classes that can be submitted to an
OperationQueue, just like you'd submit a closure of work to a DispatchQueue for
GCD. Because they’re classes and can contain variables, you gain the ability to know
what state the operation is in at any given point.
• isReady
• isExecuting
• isCancelled
• isFinished
Unlike GCD, an operation is run synchronously by default, and getting it to run
asynchronously requires more work. While you can directly execute an operation
yourself, that’s almost never going to be a good idea due to its synchronous nature.
You'll want to get it off of the main thread by submitting it to an OperationQueue so
that your UI performance isn’t impacted.
Bonus features
But wait, there’s more! Operations provide greater control over your tasks as you can
now handle such common needs as cancelling the task, reporting the state of the
raywenderlich.com 24
Concurrency by Tutorials Chapter 2: GCD & Operations
BlockOperation
Sometimes, you find yourself working on an app that heavily uses operations, but
find that you have a need for a simpler, GCD-like, closure. If you don’t want to also
create a DispatchQueue, then you can instead utilize the BlockOperation class.
Note: Block operations run concurrently. If you need them to run serially,
you'll need to setup a dispatch queue instead.
If you’re just working with methods or chunks of code that need to be executed, GCD
is a fitting choice. If you’re working with objects that need to encapsulate data and
functionality then you’re more likely to utilize Operations. Some developers even go
to the extreme of saying that you should always use Operations because it’s built on
top of GCD, and Apple’s guidance says to always use the highest level of abstraction
provided.
At the end of the day, you should use whichever technology makes the most sense at
the time and provides for the greatest long-term sustainability of your project, or
specific use-case.
In the next chapter, you'll take a deep dive into how Grand Central Dispatch works,
learn about the difference between threads and queues, and identify some of the
complexities that can occur when implementing concurrency in your app.
raywenderlich.com 25
Random documents with unrelated
content Scribd suggests to you:
S gyöngyét szedé vad jövevény,
Hitére is láncot tevén.
Irlandszerte Emmet Róbertre ismertek Hafedben, aki vérit ontja «Boldog honért
– szabad hitért» s «szabadságszózat bűszere» – s arájára, az angolokhoz szító
családban élő, vőlegényét holtáig gyászoló Sarah Curran-re Hindában, aki «Géber
ha vérzik, mindegyikben – kesergve holt ifját siratja». – S a legköltőibb ilyen
elbeszélésben is a Paradicsomból kitiltott péri jóvátételül egy hazáért hullott
vércseppet viszen, csak azután az anya sóhaját gyermekeért s végül – ami aztán
megnyitja előtte a menny kapuját – egy gonosztevő bűnbánó könnyét.
Oh férfiak, ha húgotok, –
Oh, anyátok, nőtök ha van;
Nem vászon, emberélet az,
Amit viseltek gondtalan.
Ölts – ölts – ölts!
Szenny, éh, rongy közt tovább!
Kettős szállal egyszerre varrsz
Inget – s halott-ruhát!…
II. A REGÉNY.