100% found this document useful (1 vote)
118 views55 pages

Get Concurrency by Tutorials Second Edition Multithreading in Swift With GCD and Operations Tutorial Team PDF Ebook With Full Chapters Now

Operations

Uploaded by

ggggghodin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
118 views55 pages

Get Concurrency by Tutorials Second Edition Multithreading in Swift With GCD and Operations Tutorial Team PDF Ebook With Full Chapters Now

Operations

Uploaded by

ggggghodin
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 55

Experience Seamless Full Ebook Downloads for Every Genre at textbookfull.

com

Concurrency by Tutorials Second Edition


Multithreading in Swift with GCD and Operations
Tutorial Team

https://textbookfull.com/product/concurrency-by-tutorials-
second-edition-multithreading-in-swift-with-gcd-and-
operations-tutorial-team/

OR CLICK BUTTON

DOWNLOAD NOW

Explore and download more ebook at https://textbookfull.com


Recommended digital products (PDF, EPUB, MOBI) that
you can download immediately if you are interested.

Design Patterns by Tutorials Third Edition Learning Design


Patterns in Swift Raywenderlich Tutorial Team

https://textbookfull.com/product/design-patterns-by-tutorials-third-
edition-learning-design-patterns-in-swift-raywenderlich-tutorial-team/

textboxfull.com

iOS 11 by Tutorials Learning the new iOS APIs with Swift 4


1st Edition The Raywenderlich Tutorial Team

https://textbookfull.com/product/ios-11-by-tutorials-learning-the-new-
ios-apis-with-swift-4-1st-edition-the-raywenderlich-tutorial-team/

textboxfull.com

RxSwift Reactive Programming with Swift Third Edition


Raywenderlich Tutorial Team

https://textbookfull.com/product/rxswift-reactive-programming-with-
swift-third-edition-raywenderlich-tutorial-team/

textboxfull.com

Server Side Swift with Vapor Building Web APIs and Web
Apps in Swift 3rd Edition Raywenderlich.Com Tutorial Team

https://textbookfull.com/product/server-side-swift-with-vapor-
building-web-apis-and-web-apps-in-swift-3rd-edition-raywenderlich-com-
tutorial-team/
textboxfull.com
Machine Learning by Tutorials Beginning Machine Learning
for Apple and iOS First Edition Raywenderlich Tutorial
Team
https://textbookfull.com/product/machine-learning-by-tutorials-
beginning-machine-learning-for-apple-and-ios-first-edition-
raywenderlich-tutorial-team/
textboxfull.com

iOS Apprentice Eighth Edition Beginning iOS Development


with Swift and UIKit Raywenderlich Tutorial Team

https://textbookfull.com/product/ios-apprentice-eighth-edition-
beginning-ios-development-with-swift-and-uikit-raywenderlich-tutorial-
team/
textboxfull.com

Design Patterns by Tutorials Learning design patterns in


Swift 4 2 Joshua Greene

https://textbookfull.com/product/design-patterns-by-tutorials-
learning-design-patterns-in-swift-4-2-joshua-greene/

textboxfull.com

Core Data By Tutorials Aaron Douglas

https://textbookfull.com/product/core-data-by-tutorials-aaron-douglas/

textboxfull.com

Simulations in Swift 5: Design and Implement with Swift


Playgrounds Beau Nouvelle

https://textbookfull.com/product/simulations-in-swift-5-design-and-
implement-with-swift-playgrounds-beau-nouvelle/

textboxfull.com
Concurrency by Tutorials

Concurrency by Tutorials
By Scott Grosch

Copyright ©2019 Razeware LLC.

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

Table of Contents: Overview


About the Cover ......................................................................................... 8
Acknowledgements ............................................................................... 12
What You Need ........................................................................................ 13
Book License ............................................................................................. 14
Book Source Code & Forums ............................................................. 15
Section I: Getting Started with Concurrency ............ 17
Chapter 1: Introduction ........................................................... 18
Chapter 2: GCD & Operations .............................................. 21
Section II: Grand Central Dispatch ............................... 27
Chapter 3: Queues & Threads ............................................... 28
Chapter 4: Groups & Semaphores ....................................... 40
Chapter 5: Concurrency Problems ...................................... 49
Section III: Operations ...................................................... 57
Chapter 6: Operations .............................................................. 58
Chapter 7: Operation Queues ............................................... 69
Chapter 8: Asynchronous Operations ............................... 76
Chapter 9: Operation Dependencies.................................. 87
Chapter 10: Canceling Operations ...................................... 97
Section IV: Real-Life Concurrency ............................. 103
Chapter 11: Core Data .......................................................... 104
Chapter 12: Thread Sanitizer .............................................. 110

raywenderlich.com 3
Concurrency by Tutorials

Conclusion .............................................................................................. 115

raywenderlich.com 4
Concurrency by Tutorials

Table of Contents: Extended


About the Cover . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
About the Author . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
About the Editors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
About the Artist. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
What You Need . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
Book License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Book Source Code & Forums . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Section I: Getting Started with Concurrency . . . . . . . 17
Chapter 1: Introduction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
What is concurrency? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Why use concurrency? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
How to use concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Chapter 2: GCD & Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Grand Central Dispatch. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Which should you use? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

Section II: Grand Central Dispatch . . . . . . . . . . . . . . . . . 27


Chapter 3: Queues & Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
Threads . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Dispatch queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
Image loading example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
DispatchWorkItem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38

raywenderlich.com 5
Concurrency by Tutorials

Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39


Chapter 4: Groups & Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
DispatchGroup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41
Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
Chapter 5: Concurrency Problems . . . . . . . . . . . . . . . . . . . . . . . . . . 49
Race conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
Deadlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
Priority inversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56

Section III: Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57


Chapter 6: Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
Reusability . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
Operation states . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
BlockOperation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
Subclassing operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Chapter 7: Operation Queues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
OperationQueue management . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Fix the previous project . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
Chapter 8: Asynchronous Operations . . . . . . . . . . . . . . . . . . . . . . . 76
Asynchronous operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
Networked TiltShift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
Chapter 9: Operation Dependencies . . . . . . . . . . . . . . . . . . . . . . . . 87
Modular design . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Specifying dependencies. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 88
Watch out for deadlock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
Passing data between operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

raywenderlich.com 6
Concurrency by Tutorials

Updating the table view controller . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93


Where to go from here?. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
Chapter 10: Canceling Operations . . . . . . . . . . . . . . . . . . . . . . . . . . 97
The magic of cancel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
Cancel and cancelAllOperations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Updating AsyncOperation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
Canceling a running operation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

Section IV: Real-Life Concurrency . . . . . . . . . . . . . . . . 103


Chapter 11: Core Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
NSManagedObjectContext is not thread safe . . . . . . . . . . . . . . . . . . . . . . 105
Importing data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
NSAsynchronousFetchRequest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
Sharing an NSManagedObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Chapter 12: Thread Sanitizer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
Why the sanitizer? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Getting started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
Enabling sanitization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
It’s not code analysis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Xcode keeps getting smarter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
Where to go from here? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114
Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

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.

In looking at a starfish, however, things get a little trickier.

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.

These marine invertebrates, including the Royal Starfish (Astropecten articulatus)


that is found on the cover of this book, operate in the spirit of concurrency, having
adapted so that the parts of their bodies have multiple functions — feet that help it
move, feel, see and breathe, for example — for a simple but optimal life.

Because of their adaptability and optimization of function, seastars are considered


ecologically important as they, like the operations in this book, help their
environment to be cleaner and more efficient.

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.

Learn more about the Royal Starfish, here: https://en.wikipedia.org/wiki/


Astropecten_articulatus.

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

About the Author


Scott Grosch is the author of this book. He has been involved with
iOS app development since the first release of the public SDK from
Apple. He mostly works with a small set of clients on a couple large
apps. During the day, Scott is a Solutions Architect at a Fortune 500
company in the Pacific Northwest. At night, he's still working on
figuring out how to be a good parent to a toddler with his wife.

About the Editors


Marin Bencevic is the tech editor of this book. He is a Swift and
Unity developer who likes to work on cool iOS apps and games,
nerd out about programming, learn new things and then blog
about it. Mostly, though, he just causes SourceKit crashes. He also
has a chubby cat.

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
Concurrency by Tutorials About the Cover

About the Artist


Vicki Wenderlich is the designer and artist of the cover of this
book. She is Ray’s wife and business partner. She is a digital artist
who creates illustrations, game art and a lot of other art or design
work for the tutorials and books on raywenderlich.com. When she’s
not making art, she loves hiking, a good glass of wine and
attempting to create the perfect cheese plate.

raywenderlich.com 11
A Acknowledgements

We'd like to thank:

Luke Freeman for coordinating and/or creating many of the images that you see in
this book.

Amy Sawatzky for her editorial assistance to the author.

raywenderlich.com 12
W What You Need

To follow along with this book, you’ll need the following:

• 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

• An intermediate level knowledge of Swift. This book teaches concurrency when


building iOS applications using Swift. You could use the knowledge acquired in
this book for your Objective-C codebase, but this book won’t include any
Objective-C examples. You could also use this knowledge for your macOS, tvOS
and watchOS apps, but like Objective-C, this book won’t include any examples for
these platforms.

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

By purchasing Concurrency by Tutorials, you have the following 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

If you bought the digital edition


The digital edition of this book comes with the source code for the starter and
completed projects for each chapter. These resources are included with the digital
edition you downloaded from store.raywenderlich.com.

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

If you bought the print version


You can get the source code for the print edition of the book here:

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

Digital book editions


We have a digital edition of this book available in both ePUB and PDF, which can be
handy if you want a soft copy to take with you, or you want to quickly search for a
specific term within the book.

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.

Visit our book store page here:

• 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 [email protected] 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.

Chapter 2: GCD vs. Operations: GCD vs.Operations: Concurrency can be handled


by either Grand Central Dispatch (GCD) or Operations. Learn about the differences
between the two and why you might choose one over the other.

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

Why use concurrency?


It’s critical to ensure that your app runs as smoothly as possible and that the end
user is not ever forced to wait for something to happen. A second is a minuscule
amount of time for most everything not related to a computer. However, if a human
has to wait a second to see a response after taking an action on a device like an
iPhone, it feels like an eternity. "It’s too slow" is one of the main contributors to your
app being uninstalled.

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.

How to use concurrency


That’s the focus of this book! At a high level you need to structure your app so that
some tasks can run at the same time. Multiple tasks that modify the same resource
(i.e., variable) can’t run at the same time, unless you make them thread safe.

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.

Where to go from here?


Well to the next page of course! Hopefully as you work through the following
chapters you’ll gain an appreciation for what concurrency can do for your app and
why your end users will appreciate the extra effort you put into making the app
perform as fast as possible. Knowing when to use Grand Central Dispatch as opposed
to an Operation subclass early in the app lifecycle will save you hours of rework
down the road.

raywenderlich.com 20
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

Grand Central Dispatch


GCD is Apple’s implementation of C’s libdispatch library. Its purpose is to queue up
tasks — either a method or a closure — that can be run in parallel, depending on
availability of resources; it then executes the tasks on an available processor core.

Note: Apple’s documentation sometimes refers to a block in lieu of closure,


since that was the name used in Objective-C. You can consider them
interchangeable in the context of concurrency.

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.

Synchronous and asynchronous tasks


Work placed into the queue may either run synchronously or asynchronously.
When running a task synchronously, your app will wait and block the current run
loop until execution finishes before moving on to the next task. Alternatively, a task
that is run asynchronously will start, but return execution to your app immediately.
This way, the app is free to run other tasks while the first one is executing.

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:

// Class level variable


let queue = DispatchQueue(label: "com.raywenderlich.worker")

// Somewhere in your function


queue.async {
// Call slow non-UI methods here

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.

Serial and concurrent queues


The queue to which your task is submitted also has a characteristic of being either
serial or concurrent. Serial queues only have a single thread associated with them
and thus only allow a single task to be executed at any given time. A concurrent
queue, on the other hand, is able to utilize as many threads as the system has
resources for. Threads will be created and released as necessary on a concurrent
queue.

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.

Asynchronous doesn’t mean concurrent


While the difference seems subtle at first, just because your tasks are asynchronous
doesn’t mean they will run concurrently. You’re actually able to submit asynchronous
tasks to either a serial queue or a concurrent queue. Being synchronous or
asynchronous simply identifies whether or not the queue on which you’re running
the task must wait for the task to complete before it can spawn the next task.

raywenderlich.com 23
Concurrency by Tutorials Chapter 2: GCD & Operations

On the other hand, categorizing something as serial versus concurrent identifies


whether the queue has a single thread or multiple threads available to it. If you think
about it, submitting three asynchronous tasks to a serial queue means that each task
has to completely finish before the next task is able to start as there is only one
thread available.

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.

Operations can exist in any of the following states:

• 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

task, wrapping asynchronous tasks into an operation and specifying dependences


between various tasks. Chapter 6, "Operations," will provide a more in-depth
discussion of using operations in your app.

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.

BlockOperation subclasses Operation for you and manages the concurrent


execution of one or more closures on the default global queue. However, being an
actual Operation subclass lets you take advantage of all the other features of an
operation.

Note: Block operations run concurrently. If you need them to run serially,
you'll need to setup a dispatch queue instead.

Which should you use?


There’s no clear-cut directive as to whether you should use GCD or Operations in
your app. GCD tends to be simpler to work with for simple tasks you just need to
execute and forget. Operations provide much more functionality when you need to
keep track of a job or maintain the ability to cancel it.

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
Concurrency by Tutorials Chapter 2: GCD & Operations

Where to go from here?


To the next chapter, of course! The rest of the book will examine, in detail, both
Grand Central Dispatch and Operations. By the time you’ve completed the book
you'll have a solid grasp on what both options provide, as well as a better idea on how
to choose one over the other.

raywenderlich.com 26
Section II: Grand Central
Dispatch

In this section, you'll take a deep dive into Apple's most popular and easy-to-use
mechanism to write and manage concurrent tasks — Grand Central Dispatch. You'll
learn how to utilize queues and threads to control the execution of tasks in your app,
as well as how to group these tasks together. You'll also learn about common pitfalls
and dangers of using concurrency, and how you can avoid them.

Chapter 3: Queues & Threads: This chapter teaches you how to use a GCD queue
to offload work from the main thread. You'll also learn what a "thread" is.

Chapter 4: Groups & Semaphores: In the previous chapter you learned about how
queues work. In this chapter you'll expand that knowledge to learn how to submit
multiple tasks to a queue, which need to run together as a "group" so that you can be
notified when they have all completed. You'll also learn how to wrap an existing API
so that you can call it asynchronously.

Chapter 5: Concurrency Problems: By now you know how GCD can make your app
so much faster. This chapter will show you some of the dangers of concurrency if
you're not careful, and how to avoid them.

raywenderlich.com 27
3 Chapter 3: Queues &
Threads

Dispatch queues and threads have been mentioned a couple of times now, and you’re
probably wondering what they are at this point. In this chapter, you’ll get a much
deeper understanding of what Dispatch queue and Threads are, and how to best
incorporate them in your development workflow.

raywenderlich.com 28
Concurrency by Tutorials Chapter 3: Queues & Threads

Threads
You’ve probably heard the term multithreading at some point, yes? A thread is
really short for thread of execution, and it’s how a running process splits tasks
across resources on the system. Your iOS app is a process that runs multiple tasks by
utilizing multiple threads. You can have as many threads executing at once as you
have cores in your device’s CPU.

There are many advantages to splitting your app’s work into multiple threads:

• Faster execution: By running tasks on threads, it’s possible for work to be done
concurrently, which will allow it to finish faster than running everything serially.

• Responsiveness: If you only perform user-visible work on the main UI thread,


then users won’t notice that the app slows down or freezes up periodically due to
work that could be performed on another thread.

• Optimized resource consumption: Threads are highly optimized by the OS.

Sounds great, right? More cores, more threads, faster app. I bet you’re ready to learn
how to create one, right? Too bad! In reality, you should never find yourself needing
to create a thread explicitly. The OS will handle all thread creation for you using
higher abstractions.

Apple provides the APIs necessary for thread management, but if you try to directly
manage them yourself, you could in fact degrade, rather than improve, performance.
The OS keeps track of many statistics to know when it should and should not allocate
or destroy threads. Don’t fool yourself into thinking it’s as simple as spinning up a
thread when you want one. For those reasons, this book will not cover direct thread
management.

Dispatch queues
The way you work with threads is by creating a DispatchQueue. When you create a
queue, the OS will potentially create and assign one or more threads to the queue. If
existing threads are available, they can be reused; if not, then the OS will create
them as necessary.

raywenderlich.com 29
Another Random Scribd Document
with Unrelated Content
fell around him. Suddenly he dropped, and hearts sank, thinking his
brief career ended; but he had only tripped over some obstacle. Often
he stumbled, sometimes he fell prostrate, but was quickly up again,
and finally disappeared limping, over the summit, and the Fifty-fifth
saw him no more for several months. As the boy sped away the last
time, the colonel shouted to him: “Bring calibre fifty-four.” General
Sherman’s letter to the War Department will tell the rest of the story.

Headquarters Fifteenth Army Corps,


Camp on Big Black, Aug. 8th, 1863.

Hon. E. M. Stanton, Secretary of War,


Sir:

I take the liberty of asking through you that something be done for a young lad
named Orion P. Howe, of Waukegan, Illinois, who belongs to the 55th Illinois, but
is at present from home, wounded. I think he is too young for West Point, but
would be the very thing for a midshipman.
When the assault at Vicksburg was at its height, on the 19th of May, and I was
in front near the road which formed my line of attack, this young man came up to
me wounded and bleeding, with a good, healthy boy’s cry: “General Sherman,
send some cartridges to Colonel Malmborg, the men are all out.” “What is the
matter, my boy?” “They shot me in the leg, sir, but I can go to the hospital. Send
the cartridges right away.” Even where we stood the shot fell thick, and I told him
to go to the rear at once, I would attend to the cartridges, and off he limped. Just
before he disappeared on the hill, he turned and called to me as loud as he could:
“Calibre 54.”
I have not seen the boy since, and his colonel gave me his address as above, and
says he is a bright, intelligent boy, with a fair preliminary education. What
arrested my attention there, was, and what renews my memory now, is, that one
so young, carrying a musket-ball wound through his leg, should have found his
way to me on that fatal spot, and delivered his message, not forgetting the very
important part even of the calibre of the musket, 54, which you know is an
unusual one. I’ll warrant the boy has in him the elements of a man, and I
commend him to the government as one worthy the fostering care of some of its
national institutions.
I am, with respect, your obedient servant,

W. T. Sherman,
Major-General Commanding.

BE PATRIOTIC.
It may be, my boy, that you will never be able to guide a regiment
of soldiers as did Nathan Beman, or carry cartridges as did young
Howe, but that is no reason why you should not be just as patriotic.
That boy who is law abiding, who opposes everything that tends to
undermine the national fabric, who decries Sabbath desecration, vile
language, bad literature, and all vices, is a patriot in the true sense of
the word, and can be relied upon in times of peace as well as war to
do his best for the country.
Be patriotic. Cultivate the spirit of admiration toward the national
flag. Dowered with priceless traditions its stars and stripes speak of
the sufferings of the past, the prosperity of the present, and the
glories of the future which shall attend the onward march of this
great Republic. It is the hallowed emblem of the world’s greatest
nation, and of its most resplendent civilization. Of Sherman it was
said that he never failed to salute the flag by taking off his hat in its
presence. That flag is the emblem of all we are and all we expect to
be.
“It floats that all the rights of men may every people bless
And God’s own kingdom walk the world in peace and righteousness.”

Be patriotic. Study the questions that have a bearing upon the


well-being of the people. In the past hundred years, more than
twenty-three million foreigners have settled in this land. Many are
God-fearing men, but many more are entirely out of harmony with
our principles and institutions. Truly America is
“The mother with the ever open door,
The feet of many nations on her floor,
And room for all the world about her knees.”

Of the seventy million inhabitants twenty-five per cent. are yet in


gross ignorance, thirteen per cent. cannot read the ballots they cast,
and thousands of such are annually coming to our shores, imbued
with the notions, failings and vices of their native lands. True
patriotism desires and labors not only for a free people, but an
educated one.
To be patriotic requires candor. We must be fair in our judgment
of others who may differ from us concerning methods of dealing with
some vital questions which are always before the nation. We do not
always see and understand alike, but we must strive to promote and
preserve the integrity of the nation. In the opening hours of the
French Revolution Mirabeau roused the rabble of Paris, which
whirled the social order into chaos, provoking Madame Roland’s
dying words, “Oh, liberty, what crimes are done in thy name!” We
have Mirabeaus here, but as educated lovers of our country, we must
antagonize wrong, uphold right, and defend the principles of the
Declaration of Independence.
To be patriotic in the true sense is to permeate every question with
Christianity. It was religious liberty that became the mother of
political liberty in England. De Toqueville said, “America’s liberty
considers Christianity the guardian angel of her struggle and victory,
the cradle of her life, the Divine source of her right.” “God and my
country” is the true patriot’s cry. In the words of the almost forgotten
Oliver Ellsworth to the Grand Jury of Savannah in 1779, “Let us rear
an empire sacred to the rights of men; and commend a government
of reason to the nations of the earth.”
PART III
Relation to God
CHAPTER XXI
Be a Christian

INTRODUCTION TO CHAPTER XXI

By Samuel Fallows
“Early let me seek Thy favor;
Early let me do Thy will;
Blessed Lord, and only Savior,
With Thy love my bosom fill;
Blessed Jesus,
Thou hast loved me, love me still.”

What is it to be a Christian? It is to be born again. What is it to be


born again? The New Testament gives the answer. He that “believeth
that Jesus is the Son of God is born of Him.” (1 John 5:1). He “that
loveth is born of God.” (1 John 4:7). He “that doeth righteousness is
born of Him.” (1 John 2:29).
Faith, love righteousness and trust in Christ, love for Christ, right
deeds through this faith and love in every sphere of life, deeds of
justice, of mercy, of goodness, of purity, of charity for the welfare of
his fellowmen,—these make a Christian.
Be such a Christian, my boy. Be a trusting, brave, noble, strong,
gentle, pure, loving and self-sacrificing follower of Jesus Christ.
CHAPTER XXI
Be a Christian

Having fairly embarked on the voyage which ceases not till the port
of eternity is reached, it is an exhibition of good seamanship to take
one’s bearings. By the log is estimated the progress of the vessel; by
the compass, the direction the ship is pursuing, and by the altitude of
the stars the latitude in which it is. In like manner the Moral
chapters indicate the progress boys should make; the Social, the
course they should take, and the Religious, the latitude in which they
should live. Of these the religious are the most essential, for a boy
cannot be truly religious without being moral and social.
When the Rebellion began a young man went to his mother and
said: “Mother, may I volunteer? I argue the matter in four plain
ways. First, my country needs me. Second, she calls me. Third, I am
able to go. Fourth, I am willing. This makes the duty very clear to me,
unless you interpose a veto, and I think you are too good a patriot to
do that.” She gave her consent, and before he departed, she said:
“You know, my son, how much I have wished to see you a Christian.
Now I want you to look at the claims of Jesus exactly as you have
looked at those of your country, simply and honestly, and see if those
same four plain propositions will not lead you into the service of
heaven.” “I’ll think of it, mother,” was his answer, and they parted.
He did not forget his promise. On his first Sabbath in camp he
resolutely set himself to the fulfilment of his mother’s request.
Remembering how he had argued duty to his country, he brought
before his mind in the same manner the subject of the divine claims
upon his heart and life. “Does Jesus want me? Does He call me? Am I
able to serve Him? Am I willing?” With an open Bible, the first three
questions were quickly answered. At the last one he hesitated, but
duty seemed so clear that he dared not falter, and falling on his knees
he gave himself to Christ. The next letter home announced him to be
a Christian soldier.

A CHRISTIAN.
Many names and titles are significant, but none means so much or
has so much honor attached to it as the word “Christian.” Young
said, “A Christian is the highest style of man.” A Christian is a Christ-
lover and a Christ-worshipper, because he sees God in Christ, and in
the God-man he sees the world’s Redeemer and his own personal
Saviour. He lives in the world, but is not of the world. While in the
world he blesses it by living a godly, upright life. His life work and
influence are a benediction to those among whom he moves. His
purpose is “not to make a living,” as Governor Russell, of
Massachusetts, used to say, “but to make a life.” He is far more
concerned about this than about dying. Death is the least of his
concerns. To live is Christ, and because of this, his life is proof of his
profession.

HOW TO BE A CHRISTIAN.

To become a Christian is not a hard matter, though to live the life


of one is a battle with the world, the flesh and Satan. It is because of
the simple rules laid down whereby one can become a Christian that
many of mature life neglect it. Were it culture, polish, or liberality,
many more would be enrolled as Christians, but because a change of
heart, affections or living is demanded, many cling to their ordinary
life, but at the last deplore it, earnestly pleading for forgiveness and
acceptance by Christ.
Three propositions are given in the New Testament, which,
accepted, will lead any boy to know what it is to be a Christian. First,
repentance: “Jesus came into Galilee, preaching ... repent ye.” (Mark
1:14, 15). Repentance means such sorrow for past conduct as leads to
amendment of life. Second, confession of sin. “If we say we have no
sin, we deceive ourselves, and the truth is not in us. If we confess our
sins, He is faithful and just to forgive us our sins, and to cleanse us
from all unrighteousness.” (1 John 1:8, 9). Third, faith in Christ to
save. Paul said to the jailer, “Believe on the Lord Jesus Christ, and
thou shalt be saved.” (Acts 16:31).
A father and son were once following a perilous path among the
Alps. In passing along they gathered some beautiful flowers, but the
boy, seeing a lovely one waving in the breeze, thoughtlessly hurried
to secure it. His foot slipped and he rolled down an incline until he
was stopped by some tall bushes. With all his strength he seized hold
of the shrubbery and commenced to call for help. The brush grew on
the brink of a yawning abyss. It was impossible for the father to
reach his son with his hands, but he carried a staff on one end of
which was an iron hook. The boy had around him a leathern belt, so
the father reached down and fastened the hook in his girdle. The lad,
however, could not be drawn up without releasing his hold on the
bushes. He could not see his father, nor did he in his fright even feel
that his father held him up; he only heard his voice: “Let go of the
bushes, my son, and I will save you.” To the boy it seemed as though
he would thus hurry himself to destruction, but, relying on his
father’s word, he forsook his hold and was drawn in safety to his
father’s side.
That boy was saved through faith. His firm belief in his father’s
word saved him. Had he persisted in holding on to the bushes
through doubt or hesitation it would have meant his death. To be
saved, every boy must forsake his hold on sin, yield himself to
Christ’s power and mercy, and then will he find to his joy, that Christ
saves to the uttermost. (Heb. 7:25).

THE TIME TO BE A CHRISTIAN.

Solomon said there is “a time to every purpose under the heaven,”


(Eccl. 3:1) and no purpose is greater and no time more important
than when a boy becomes a Christian. Youth is the most important
period of one’s life. It is the time when the faculties are most
susceptible, heart tender and will pliable; the time when tastes and
biases are created, habits acquired and character formed for future
weal or woe. No other period affords greater possibilities of long
usefulness as well as opportunities for peculiar usefulness.
A staff-officer, riding over the field of battle during the Civil War,
was attracted by a body lying under a tree, handsomely dressed, with
a fancy sword. He removed the covering and looked into the sweetest
and handsomest face he had ever seen. It was that of a boy, a
temporary aide to some officer. In his pocket was found a Testament
in which was written “James Simmons, N. Y. My son, ‘Remember
now thy Creator in the days of thy youth.’” (Eccl. 12:1).
That is it, youth. The best and most profitable time for piety.
Jeremiah and John the Baptist loved and worshipped God in their
youth. Josiah knew the Lord at eight years of age. Timothy knew the
Scriptures and loved Christ from a child. Polycarp accepted Christ at
nine, Jonathan Edwards at seven, Isaac Watts at nine, Adam Clarke
at four, William Penn at nine, Matthew Henry at eleven, Robert Hall
at twelve, Augustus Toplady at sixteen, while Joseph Griggs not only
became a Christian very young but wrote the hymn—
“Jesus! and shall it ever be
A mortal man ashamed of Thee!”

when but ten years of age.


Some years ago the “Golden Rule” sent letters of inquiry to
prominent men of the land asking several questions, one of which
was: “At what age did you become a Christian?” It was found on
receiving the answers that out of one hundred and forty-nine less
than one in ten became Christians later than twenty years of age;
twenty-nine were so young that they did not remember; at least
sixty-three professed Christ before they were eighteen. Nine-tenths
of all saved persons are saved before twenty. “Why this?” you ask.
Physiologists say “the cells of the brain change as we grow old until
finally there are ruts in them.” Carlyle explains it thus: “In younger
years the whole mind is, as it were, fluid, and capable of forming
itself into any shape that the owner of the mind pleases. The mind is
in fluid state, but it hardens up gradually to the consistency of rock
or iron, and you cannot alter the habits of the old man, for as he
began he will go on to the last.” To procrastinate in youth is to
jeopardize one’s soul in age.

“REMEMBER.”

“Remember now thy Creator in the days of thy youth,” (Eccl. 12:1)
is the most important exhortation of the Old Testament. Remember
is just the opposite of forget, and the one to remember is the most
exalted and important in the universe, “thy Creator.” Remember His
Word and believe it, for the promise is: “He that heareth My Word
and believeth on Him that sent Me, hath everlasting life.” (John
5:24). Remember His work and accept it, for He was made to “sin for
us, Who knew no sin; that we might be made the righteousness of
God in Him.” (2 Cor. 5:21). Remember His love and return it, for
“herein is love, not that we loved God, but that He loved us,” (1 John
4:10) and “gave His only begotten Son, that whosoever believeth in
Him should not perish but have everlasting life.” (John 3:16).
Remember this Creator now. Only one time is mentioned in the
Scriptures at which eternal life is promised. Cowley sang of an
“everlasting now,” but there is no such time, and no wise boy desires
that there shall be. There is an eternity of the past, an eternity of the
future, but “now” is limited to now. “Behold, now is the accepted
time; behold, now is the day of salvation.” (2 Cor. 6:2). And this—
“Opportunity lost, however deplored
Is eternity gone and is never restored.”

After the overthrow of the French empire by the Germans, Prince


Napoleon joined the English army, and went among the savage tribes
of South Africa. One day while with a squad of soldiers outside the
camp, he was warned by one of the company, who said: “We had
better return. If we don’t hasten we may fall into the hands of the
enemy.” “Oh,” said the Prince, “let us stay here ten minutes and
drink our coffee.” Before the ten minutes had passed a company of
Zulus came upon them and in the skirmish the Prince lost his life.
His mother, when informed of the facts, said, “That was his great
mistake from boyhood. He never wanted to go to bed at night in
time, nor to arise in the morning. He was ever pleading for ten
minutes more. On this account I sometimes called him ‘Mr. Ten
Minutes.’”
The habit of delay was to him what it is to thousands who pass the
tenth, fifteenth and twentieth milestone without accepting Christ, his
ruination. Such delay weakens the force of the will, unfits for action
when opportunity presents, robs the present and blasts the future.

REASONS FOR BEING A CHRISTIAN IN YOUTH.


“If youth,” as Ruskin said, “is essentially one of formation,
edification, instruction,” then is it the proper time to be a Christian,
for “There’s never an hour of it but is trembling with destinies, not a
moment of which, once past, the appointed work can ever be done
again, or the neglected blow struck on cold iron.”
A boy should be a Christian for the sake of safety. As one grows
away from boyhood, he grows away from the opportunities for
salvation. He is liable to drift. There is a point on Niagara River
called “Past Redemption Point,” where the current is too strong for
human power to battle against. Manhood and age have no special
promise like “they that seek Me early shall find Me.” (Prov. 8:17).
A boy should be a Christian that he may be happy. To properly
remember God, to lose oneself in adoration of Him, is to be like Him,
to be “holy as He is holy,” (1 Pet. 1:15, 16) consequently it is to be
happy as He is happy. Holiness and happiness are inseparable. True
love and true joy come together.
A boy should be a Christian to be useful. God’s promise to
Abraham was: “I will bless thee, and thou shalt be a blessing.” (Gen.
12:2). When Joseph dwelt in Potiphar’s house, we read: “The Lord
blessed the Egyptian’s house, for Joseph’s sake.” (Gen. 39:5). And
the boy who loves Christ will be a rich blessing in many ways to
others.
A boy should be a Christian because it is right. Right is better than
might, and worth more than gold. “In the matter of right,” said
Martin Luther, “I will take my stand, I yield to none.” “I’d rather be
right than President,” said Henry Clay. The only proper life to live is
the Christian life. It is sweet on earth, which makes heaven the
sweeter.
My boy, be a Christian. “All men at the head of great movements,”
said Mr. Gladstone, “are Christian men. During the many years I was
cabinet officer, I was brought into association with sixty master
minds, and all but five were Christians.” To be a Christian is the most
satisfactory, honorable, influential course to pursue. It gives
unspeakable joy in life, peace in death, and glory hereafter.
Remember then—
God wants the boys—all kinds of boys—
To love Him, serve Him, do His will;
He wants those boys that make much noise,
And those who keep so very still.

God sent His Son to die for all,


And on the cross His blood was shed.
No boy need spurn His gracious call
Or of the “Bread of Life” be fed.

Then why not to this Christ now flee


And on His mercy cast thyself?
O hear His words: “Come unto Me,”
And answering back, “I yield myself.”
CHAPTER XXII
Be Prayerful

INTRODUCTION TO CHAPTER XXII

By A. C. Lorimer, D. D.
When I was a youth, I loved to climb Arthur’s Seat early in the
morning, for the purpose of breathing the air borne to our inland
home from out the mighty seas; and so it is well for every lad each
day to seek the summit of highest faith, that he may hold
communion with God; that he may inhale something of the
atmosphere of eternal worlds.
It is said that Daniel opened his window when he prayed, toward
Jerusalem. It was doubtless that he might think of the hallowed city.
Better far, however, to open the windows of the soul toward heaven,
not merely that we may think of the hereafter, but that the invisible,
at the present moment, may stream into our being.
Prayer is the soul’s voice. It is the aspiration of the highest part of
man. It is the sublime confidence, that, though foreign, still it is
within the range of possibility to hold communion with the Creator
of us all. Every time we bend the knee before the Throne of Grace, we
declare our belief in our own God-likeness and in our indestructible
affinity for the divine. Therefore, pray, my boy, and keep on praying;
for it is the true Jacob’s ladder that will lead you, round by round, up
to the Everlasting Throne.
CHAPTER XXII
Be Prayerful

A noble characteristic of any boy is love for prayer. Too many


consider common amusements more important than going to some
chamber or church to commune with the loving Saviour. They are
not. The former bring transient happiness and with it a weary frame,
the latter an unexplained peace, rest of body and soul. The former
gratifies for a time without changing selfish desires or promoting
lofty aspirations, the latter moulds into the image of the Christ-
character.
Prayer is not simply a petition or mere forms of a vain repetition.
It is a turning of the life toward God, an opening of the soul toward
heaven, a reaching out of one’s being with desire to appropriate the
Divine. It was a shoemaker’s shop, with bench, half-worn shoes and
not a few boxes. The proprietor was an old friend of the writer, so
deaf that few could converse with him. Visiting the village in which
he lived, I called upon him. After a chat by means of the lips, signs
and paper, he asked if I would like to hear his son play the harp.
Assenting, he called the lad, who brought a beautiful instrument.
Placing his feet on the pedals, he ran his fingers over the wires and
melodious music resounded. When it stopped, I turned to the old
man, and asked by signs: “Did you hear it?” Shaking his head, he
answered, “Not a note.” Then stepping to the stove, he picked up a
long black poker, and putting one end between his teeth and the
other on the harp, he motioned the boy to play. The lad’s fingers
moved as if by magic. The room was flooded with music and passing
pedestrians stopped to listen. Suddenly the musician stopped. I
propounded the same question: “Did you hear anything?” He
laughed and answered: “All that you heard, I heard.” How? That
dirty poker was changed into a conductor of sound. It brought harp
and listener in contact with each other. In like manner prayer brings
God and petitioner into near relation. What one pleads, the other
hears, and answering, God makes music in the soul.

GREAT MEN GREAT IN PRAYING.


Many great men have been great in praying. Men of the Bible, men
of science, history and influence have been firm believers in it.
Charles Simeon and Joseph Alleine spent from four to eight o’clock
in the morning waiting upon God. Wesley gave two hours a day,
Luther the first three hours. Samuel Rutherford was up at three in
the morning to give God praise. Archbishop Leighton was so much
alone with God that he seemed to be in a perpetual meditation.
Bishop Ken was so much alone with God, that his soul was said to be
God-enamored. David Brainerd prayed hour after hour. John
Fletcher spent whole nights in prayer, John Welsh often seven to
eight hours a day. When the hour for devotion arrived, General
Gordon displayed a white handkerchief outside his tent, and as long
as it remained, no one was allowed to disturb him. General Stonewall
Jackson’s servant used to say that when his master got up several
times during the night to pray there was to be a battle next day.
Abraham Lincoln acknowledged that he had been driven to his knees
“by the overwhelming conviction that he had nowhere else to go.”
Gathering his pupils about him at the opening of his school, Agassiz
said, “It is becoming that we first of all bow in the presence of the
Infinite One.” Well might these exclaim with thousands of others:
“For this cause I bow my knees unto the Father of our Lord Jesus
Christ.” (Eph. 3:14).

PRAYER MAKES A BOY BRAVE.

During the Civil War a dozen soldiers were playing cards one night
when one exclaimed: “What on earth was that?” Listening attentively
a moment, he heard a low, solemn voice, coming from the next tent,
occupied by several recruits, who had that day arrived in camp.
Accompanied by the others he approached the tent on tip-toe. “Boys,
he’s praying, or I’m a sinner!” he roared out. “Three cheers for the
parson!” shouted another man of the group as the prayer ended.
“You watch things for three weeks. I’ll show you how to take the
religion out of him,” said the first speaker, laughing. He was a large
burly fellow, prominent in mischief. The recruit was a slight, pale-
faced boy. During the next three weeks the latter was the butt of the
camp. Then several of the boys, conquered by the lad’s gentle
patience and uniform kindness, begged the others to stop annoying
him. “Oh, the little ranter is no better than the rest of us!” answered
the ringleader. “When we get under fire, you’ll see him run. These
pious folk don’t like the smell of gunpowder. I’ve no faith in their
religion.”
In a few weeks, the regiment broke camp, marched toward
Richmond, entered the Wilderness and engaged in that fearful battle.
The company to which the young recruit belonged had a desperate
struggle. The brigade was driven back, and when the line was formed
behind the breastworks they had built in the morning, he was
missing. When last seen, he was surrounded by enemies, fighting
desperately. At his side was the brave fellow who had made the poor
lad a constant object of ridicule. Both were given up as lost. Suddenly
the big man was seen tramping through the underbrush, bearing the
dead body of the boy. Reverently he laid the corpse down, saying as
he wiped the blood from his own face: “Boys, I couldn’t leave him
behind, he fought so. I thought he deserved a decent burial.”
During a lull in the battle the men dug a shallow grave and
tenderly laid him to rest. Then, as one was cutting the name and
regiment upon a board, the big man said, with a husky voice, “I guess
you’d better put the words ‘Praying soldier’ in somewhere. He
deserves the title, and maybe it’ll console him for our abuse.”
There was not a dry eye among those rough men as they stuck the
rudely carved board at the head of the grave. “Well,” said one, “he
was a praying Christian soldier if ever there was one! And,” turning
to the ringleader, “he didn’t run, did he, when he smelt gunpowder?”
“Run!” answered the big man, his voice tender with emotion. “Why,
he didn’t budge an inch! But what’s that to standing for weeks our
fire like a man, and never sending a word back! He just stood by his
flag and let us pepper him, he did; and boys, I have made up my
mind if prayer will make a man as bold, as loving, as forgiving, as
good, as it did that boy, I’m going to resort to it. It did him good and
it’ll do me good,” and as the other fellows bent their heads he prayed
for forgiveness and salvation, at the close of which the others said,
“Amen!”

HOW TO PRAY.
Prayer is a blessed privilege, a vital necessity, an imperative duty,
but many there are who do not know how to pray. A mere repetition
of words or reading prayers is not prayer. Prayer may be a sigh, a
tear, a groan, a bungling utterance, “a true wish” as Phillips Brooks
used to say, “sent God-ward.” It is—
“the soul’s sincere desire
Uttered or unexpressed.
The motive of a hidden fire
That kindles in the breast.”

Prayer should always be accompanied by thanksgiving and


confession. David said, “I will confess my transgressions unto the
Lord,” (Psalm 32:5) and Paul exhorts, “Giving thanks always for all
things unto God and the Father in the name of our Lord Jesus
Christ.” (Eph. 5:20). Prayer should be offered in faith. Faith is taking
one at his word and thus Christ said, “If ye ask anything in My name,
I will do it.” (John 14:14). To pray without faith, the Bible informs us,
is sin, and this is the reason why many of our petitions are not
answered. They are like those blossoms which fall blasted to the
earth. They had a certain beauty and fragrance, but for want of some
conformity to the law of growth, they never developed into fruit.
They are, as Mrs. Stowe says, “drowsy mutterings of unawakened
souls, talking in their sleep.” But real prayer is always answered.
There may be delays as in Daniel’s petition, or tests to strengthen
faith, as when Jesus said to Jairus, “Fear not, only believe,” (Luke
8:50) for what Christ has promised, He will certainly perform.

WHEN AND WHERE TO PRAY.

Prayer should be our vital breath. As with Paul, it should be


“without ceasing,” (Thess. 5:17) our inward desire continually going
up to God. It should be the first exercise of the morning and the last
in the evening. “It is the first hour of the morning,” says a Chinese
proverb, “that gives color to all the others that follow.” Louis XIV.
was awakened every morning with the words: “Arise, Monsieur, you
have great things to do to-day.” But how could they be done properly
without God’s blessing, and how could God’s blessing be secured
without asking? When Arthur P. Stanley the first night went to the
dormitory at Eton School where he with others had to sleep, he knelt
down to say his evening prayers. Instantly a shower of pillows and
shoes flew about him. He prayed on. “Stanley,” said one of the boys
next day, “I ought to have done as you did. I haven’t said my prayers
at night because I was afraid of the ridicule of the boys.” It was not
long before a score of them followed his example. President Garfield
when a boy undertook with a number of students from Williams
College to climb Mount Greylock. Their plan was to spend the night
on the mount. Seated around the campfire they sang college songs
and told stories all the evening. At bedtime Garfield took a
Testament from his pocket and said: “Boys, it is my custom to read a
chapter in the Bible and have prayer before going to bed. Shall we
have it all together?” and though it seemed rather hard to do,
Garfield did it and all were blessed for it.
Two places are mentioned in the Scriptures where a boy should
pray. Those places are the Christian’s arsenal. One is the secret
chamber where communion is sweet because undisturbed, the other
is the church, where in unity believers call upon God. To the devout
boy both are the “Holy of Holies” where God delights to meet him at
the “Mercy Seat.” Blessed is the place of public prayer! Never neglect
it. But the place of secret prayer is still more blessed. Cyprian would
resort to a shady arbor where “no profane listener may hinder my
musings, and no domestic clamor drown them.” Robert Murray
McCheyne declared, “It is my noblest and most fruitful
employment.” Henry Martyn mourned at the close of his saintly life,
that he had devoted “too much time to public works and too little to
private communion with God.” God said, “In quietness and in
confidence shall be your strength.” (Isa. 30:15).
O, the sweetness of one hour at the feet of Jesus. It changes
dispositions, purifies character, overcomes obstacles, imparts
strength to resist temptations, yes, it makes life worth living.
“We kneel, and all around us seems to lower;
We rise, and all, the distant and the near,
Stands forth in sunny outline, brave and clear;
We kneel, how WEAK! we rise, how full of POWER!”

WHAT PRAYER WILL DO.


More things are wrought by prayer than anything else. It opens
heaven’s door, commands God’s ears to hear and hand to bestow,
makes darkened clouds withdraw, climbs—
“the ladder Jacob saw,
Gives exercise to faith and love;
Brings every blessing from above.”

Prayer has brought rain a thousand times since Elijah prayed,


softened kings’ hearts since Nehemiah won the sympathy of
Artaxerxes, shut lions’ mouths since Daniel was cast into their den,
given victory to armies since Amalek was discomfited, liberated
captives since Peter was delivered from prison, abated storms since
Christ said to wind and wave: “Peace! be still,” (Mark 4:39) arrested
hundreds of prodigals since Monica prayed for her wicked son
Augustine, restored health, supplied food, transformed lives and
revolutionized nations.
Prayer is the means that aids to keep in subjection the sinful
tendencies of human nature and though living in the world keeps us
separated from it. It is the means to aid us in winning souls for Jesus.
John Wesley was once riding along when he saw a man kneeling by
the wayside breaking stones. “Ah,” cried he, “I wish I could break the
hearts of some who hear me as easily as you are breaking those
stones.” The man looked up and said, “Did you ever try to break
them on your knees?” Pleading with God should always precede
pleading with souls to come to God, and it is a question whether
anyone has ever come to God who was not earnestly prayed for by
some one.
Prayer will also make a death-bed glorious. “Yea,” saith the
Psalmist, “though I walk through the valley of the shadow of death, I
will fear no evil, for Thou art with me, Thy rod and Thy staff they
comfort me.” (Psalm 23:4). A boy was dying at midnight. He had just
awakened from sleep. “Is it near morning?” he asked his father. “It
soon will be,” replied the parent. “Do you think I will get well?” “I
hope so,” sobbed the father. There was a long silence, then the lad
moved restlessly on the pillow and said, “Hold me up, father, I want
to say my prayers.” Then, clasping his hands together, he repeated:
“Our Father, which art in heaven, hallowed be Thy name, Thy
kingdom come. Thy kingdom come. I can’t remember, father! I can’t
remember!” A short time after the morning light stole into the room.
“Forever and forever,” uttered the boy and he fell asleep in death.
O, my boy, cultivate this glorious habit of praying. To be intimately
acquainted with God cheers, inspires, ennobles. An old man lay
dying. His sons stood around his bed to receive his parting counsel,
and his last blessing. He had fought the battle of life successfully;
and, so far as this world was concerned, had come out crowned with
honors. He had been a pillar in the church; his seat had never been
vacant, his hand always freely opened to every call. For months he
had been laid aside by a lingering and painful illness. “Boys,” he said,
“God has been good to me. He has given me many friends, good
children, a loving wife, and abundant means; but what I thank Him
for now most of all is this long and painful illness. Without it my life
would have been a failure; I should have gone hence without
knowing as I should the only One worth knowing. Boys, whatever
you do or whatever you leave undone, whether you make another
cent of money or not, take time to get acquainted with God.” That’s
it. So acquainted with Him that with simple words you can breathe
your heart’s desire. So acquainted as to talk with Him the first thing
in the morning and the last in the evening. So acquainted as to seek
His favor in everything and to praise Him for anything.
“Implore His aid, in His decisions rest,
Secure, what’er He gives, He gives the best.”
Welcome to our website – the ideal destination for book lovers and
knowledge seekers. With a mission to inspire endlessly, we offer a
vast collection of books, ranging from classic literary works to
specialized publications, self-development books, and children's
literature. Each book is a new journey of discovery, expanding
knowledge and enriching the soul of the reade

Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.

Let us accompany you on the journey of exploring knowledge and


personal growth!

textbookfull.com

You might also like