Middle
How is multithreading implemented on a single-core device?
sobes.tech AI
Answer from AI
On a single-core device, multithreading is emulated by the operating system through a time-slicing and context-switching mechanism.
- Time quantum: Each thread is allocated a small slice of processor time.
- Preemptive multitasking: The operating system interrupts the execution of a thread after its quantum expires or when it is waiting for resources (e.g., I/O).
- Context switching: The current thread's state (CPU registers, instruction pointer, memory state) is saved, and the next thread's state is loaded.
- Illusion of parallelism: Rapid switching between threads creates the impression that they are running simultaneously, although only one thread runs on the core at any given moment.
iOS uses frameworks such as GCD (Grand Central Dispatch) and Operation Queues, which abstract these low-level mechanisms, simplifying multithreading management for developers. GCD uses thread pools and automatically manages their lifecycle and scheduling across available processor cores (even on a single core).
For example, using GCD:
import Foundation
// Creating an asynchronous task
DispatchQueue.global(qos: .userInitiated).async {
// Code to be executed in the background thread
// On a single-core device, this code will be interleaved
// with execution of code in other threads/main thread
print("Running in the background thread")
}
// Main thread continues execution
print("Running in the main thread")
Even on a single-core device, GCD will enqueue this task and allocate time slices for execution, switching between it and the main thread (and other threads, if any) to create the illusion of parallelism.