Chapter 4. Concurrent Programming
iOS devices have two or three CPU cores (see Table 3-1). This means, even if the main thread (the UI thread) is busy updating the screen, the app can still be doing more computations in the background without the need for any context switch.
In this chapter, we explore various options for making the best use of the available CPU cores, and we’ll learn how to optimize performance using concurrent programming. We will discuss the following topics:
-
Creating and managing threads
-
The Great Central Dispatch (GCD) abstraction
-
Operations and queues
We will cover best practices and techniques for writing thread-safe, highly performant code.
Threads
A thread is a sequence of instructions that can be executed by a runtime.
Each process has at least one thread. In iOS, the primary thread on which the process is started is commonly referred to as the main thread. This is the thread in which all UI elements are created and managed. All interrupts related to user interaction are ultimately dispatched to the UI thread where the handler code is written—your IBAction methods are all executed in the main thread.
Cocoa programming does not allow updating UI elements from other threads. This means that whenever the app executes background threads for long operations such as network or other processing, the code must perform a context switch to the main thread to update the UI—for example, the progress bar indicating the task progress or the label indicating ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access