Javatpoint Logo
Javatpoint Logo

Multithreading in swift

Multithreading can be defined as the process which facilitates the CPU to create and execute concurrent threads. Typically, a CPU performs one operation at a time. However, by using multithreading, we may allow the CPU to switch between different tasks so that they can be executed simultaneously.

The switch between the threads occurs rapidly, and therefore, the user cannot notice the change. In iOS, the common example is the UI thread, since the application always sticks to its User interface despite the fact that the CPU is busy doing a lot of stuff. It is because of multithreading.

In iOS, the UI has its thread. When we execute a complex task, the UI remains unchanged. Let's think of a scenario in which we perform some uploading tasks in the background and running the app in the foreground. Here, the iPhone switches between two threads so quickly until the threads complete. Here, we do not need to perform the task sequentially since the iPhone can switch between uploading the file and drawing the screen.

GCD Concepts

GCD stands for Grand-Central-Dispatch, which is an API that is used to execute the closures on the worker pools. Here, the execution is done in the First-In-First-Out (FIFO) order.

The tasks that are to be executed by the CPU are submitted to the dispatch queue in the form of blocks by the application. This block is executed on a thread pool that is provided by the system. All the tasks in the dispatch queue are executed either sequentially or concurrently. However, the dispatch queue always maintains the FIFO order of the tasks.

This framework facilitates to execute code concurrently on the multi-core system by submitting a task to dispatch queues managed by the system.

Why use GCD?

Keeping the application responsive to the users is the most typical in modern days. However, to meet our requirements, we always keep adding the new functionalities to our application, which results in to make it slower and less user-friendly.

To make the application faster and responsive, we can use GCD to run the application threads and present the information to the user. For example, If we are parsing a big JSON file that takes 10 or 15 seconds to be parsed, then we can always run a thread that can show an activity indicator to the user so that it assumes that some tasks are being processed.

Let's look at an example in which we will dispatch a task to the main queue asynchronously.


Value = 0
Value = 1
Value = 2
Value = 3
Value = 4
Value = 5
Value = 6
Value = 7
Value = 8
Value = 9
Value = 10
"printing table of 10"

Youtube For Videos Join Our Youtube Channel: Join Now


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Trending Technologies

B.Tech / MCA