Last updated on September 25th, 2019⏱ Reading Time: 2 mins
One of the greatest improvements in the technology of Central Processing Units (CPUs) since their existence is the capability to contain multiple cores and therefore to run multiple threads, which means to serve more than one task at any given moment.
Serial execution of tasks or fake multitasking belongs to the history since many years now, and if you are not that young and remember old computers, or if you ever had the opportunity to get your hands on an old computer with an old operating system, then it’s easy to understand what I’m talking about. But, no matter how many cores a CPU contains or how much powerful it might be, it can become totally useless if developers don’t take advantage of these possibilities. And this is where multitasking and multithreaded programming gets into play. Developers not only can, but actually have to take advantage of the multitasking capabilities of the CPU on any device, and this can be done by breaking a program’s parts into chunks that will be executed in parallel on more than one threads.
The advantages are many, and the most important ones include the execution of demanding tasks in less time, best user experience, no frozen user interfaces, and so on. Think for example how awful apps would be if they had to download a bunch of images on the main thread and the UI would become totally unresponsive until that task would be over; users would never use such kind of apps.
In iOS, Apple provides two ways to do multitasking: The Grand Central Dispatch (GCD) and NSOperationQueue frameworks. Both of them work perfectly when it’s time to assign tasks to different threads, or different queues other than the main one. Which one should be use is a subjective matter, but in this tutorial we’ll focus on the first one, the GCD. No matter what, there’s one rule that should be always respected: The main thread must be always remain free so it serves the user interface and user interactions. Any time-consuming or CPU demanding tasks should run on concurrent or background queues. Maybe this is difficult for new developers to digest and apply, however it’s the way things should be.