Chapter 7. Concurrency and Multitasking

7.0. Introduction

Concurrency is achieved when two or more tasks are executed at the same time. Modern operating systems have the ability to run tasks concurrently, even on one CPU. They achieve this by giving every task a certain time slice from the CPU. For instance, if there are 10 tasks to be executed in one second, all with the same priority, the operating system will divide 1,000 milliseconds by 10 (tasks) and will give each task 100 milliseconds of the CPU time. That means that all these tasks will be executed in the same second, and will appear to have been executed concurrently.

However, with advances in technology, now we have CPUs with more than one core. This means that the CPU is truly capable of executing tasks at the same time. The operating system will dispatch the tasks to the CPU and wait until they are done. It’s that simple!

Grand Central Dispatch, or GCD for short, is a low-level C API that works with block objects. The real use for GCD is to dispatch tasks to multiple cores without making you, the programmer, worry about which core is executing which task. On Mac OS X, multicore devices, including laptops, have been available to users for quite some time. With the introduction of multicore devices such as the new iPad, programmers can write amazing multicore-aware multithreaded apps for iOS.

At the heart of GCD are dispatch queues. Dispatch queues, as we will soon see, are pools of threads managed by GCD on the host operating ...

Get iOS 8 Swift Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.