I investigated parallel programming using GCD.
macOS 10.15.7 Xcode 12.1 Swift 5.3
Every iOS application has a main thread. The main thread displays the UI and waits for events that occur. Complicated calculations in the main thread can slow down the process and freeze the app. Multithreading is useful in such cases. It is a mechanism that moves a task with a high load to a background thread and returns to the main thread when the task is completed.
A set of code blocks in parallel or in series waiting to be executed by a thread. With Swift, you only need to ** manage queues ** and you don't have to be thread-aware at all. The system is responsible for providing and allocating the ** threads needed to execute the code in the queue. ** **
Grand Central Dispatch: GCD API responsible for managing queues.
--Create a queue --Deposit the code block in the queue
The most important queue of all. ** Any block of code that affects the UI must be executed in the main queue **.
Used to queue tasks other than long-lived UI tasks. Often runs in parallel with the main UI queue.
.userInteractive
User interactive tasks are the highest priority tasks on the system. Use this level for tasks and queues that interact with users and actively update the app's user interface. For example, use it for animations or classes that interactively track events.
.userInitiated
User initiative tasks are second only to user interactive tasks in terms of system priority. Assign this class to tasks that give immediate results while the user is doing something, or tasks that prevent the user from using the app. For example, you can use this Quality-of-Service level to load the content of an email that you want users to see.
.utility
Utility tasks have a lower priority than user-initiated tasks and user interaction levels, but higher priority than background tasks. Assign this quality of service class to tasks that do not prevent users from continuing to use your app. For example, you can assign this class to long-term tasks where users do not actively follow their progress.
.background
Background tasks are the lowest priority of all tasks. Assign this level to the task or dispatch queue that your app uses to perform work while running in the background. For example, maintenance tasks or cleanup.
.default
Priority is a level between user-initiated tasks and utilities.
If the task item is executed synchronously by the sync
method, the program waits for the execution to finish before the method is called.
python
DispatchQueue.main.sync {
// Code to be executed
}
This code can be understood as "dispatching a synchronous queue to the main thread".
When a task item is executed asynchronously by the async
method, the method is called immediately.
python
DispatchQueue.global().async {
// Code to be executed
}
This code can be understood as "dispatching an asynchronous queue to a background thread".
Recommended Posts