[Book Update] How does Thread class work in Swift?
Threads are, for the most part, not used directly for app development on iOS anymore. But, sometimes, it comes up as a question on iOS interviews. This is an excerpt from the 2nd edition of my book.
This is an excerpt from the upcoming 2nd edition of my book The iOS Interview Guide. If you’re interested to hear more book updates like this and to receive draft chapters as I write them feel free to subscribe to my substack, I’ll post all the updates here.
How does Thread class work in Swift?
\label{question:swift_threads}
This is a low-level question designed to gauge a candidate's understanding of the fundamental building blocks of concurrency on Apple's platforms. Even though direct thread management is rare in modern iOS development, knowing how it works provides important historical context for appreciating higher-level abstractions like Grand Central Dispatch (GCD) and Swift Concurrency.
Expected Answer: The Thread class is a low-level, object-oriented way to manage a single thread of execution directly. It's part of the Foundation framework and provides you with manual control over creating, starting, and managing a thread's lifecycle.
You can create a new Thread object by passing it a closure or a selector and a target to execute on a separate thread. Another option is to subclass the Thread class, override the main() method in it and put the code you wish to be executed on another thread there.
```swift
let thread1 = Thread {
print("This is running on a background thread.")
}
let thread2 = Thread(target: self, selector: #selector(doWork), object: nil)
thread1.start()
thread2.start()
final class MyThread: Thread {
override func main() {
print("Executing on a custom thread subclass.")
}
}
let myThread = MyThread()
myThread.start()
```
A Thread instance's lifecycle is managed manually with the following methods:
start(): begins the execution of the thread.
cancel(): signals to the thread that it should exit. This is a cooperative mechanism (just like in Swift Concurrency); the code running on the thread must periodically check the isCancelled property and handle termination gracefully.
sleep(for:): Pauses the current thread for a specified time interval.
These days Thread is considered a legacy, low-level, solution that is most likely not what you want to go for in iOS application development. Instead, you should use more modern solutions that are built on top of the low-level Threads such as Grand Central Dispatch (GCD) and Swift Concurrency. Both of these solutions help you interact with Threads at a higher level of abstraction, where the system will manage the actual threads your work is executed on, rather than you having to manage it yourself manually. These solutions help you avoid many problems you’d encounter working with threads directly, such as:
Data Races: Thread has no built-in protection for shared mutable state. You are entirely responsible for implementing synchronization mechanisms like locks (NSLock) or mutexes, which are difficult to use correctly and can lead to data races or deadlocks. Swift's actors solve this at the language level, providing compile-time safety.
Thread Explosion: Creating too many threads can overwhelm the system, leading to excessive memory consumption and context-switching overhead, which harms performance. GCD and Swift Concurrency manage a limited pool of worker threads much more efficiently.
Lifecycle Management: Manually managing the lifecycle of each thread is complex. Forgetting to terminate a thread or handle its cancellation can lead to resource leaks. Structured concurrency provides clear, scoped lifetimes for tasks, which automatically handle cleanup and cancellation propagation.
Red Flags:
Advocating for the use of Thread for new application-level features.
Failing to identify the significant risks associated with manual thread management (, such as data races and deadlocks).
Not being aware of modern alternatives like GCD and, more importantly, Swift Concurrency with async/await and actors.
Help me make this chapter better.
What did I miss? Anything to add to make it more clear or helpful?
Your feedback directly helps shape this book into a more practical resource for the entire iOS community. Drop a comment or send me an email.