Queues are the tools for performing tasks in iOS. You should know what queues are in order to execute blocks of code either asynchronously or synchronously.
- [Instructor] We mentioned that grand central dispatch uses queues of closures to perform tasks submitted to the system. Once submitted GCD can then decide which thread to execute on. But what exactly are queues? According to Apple's documentation, queues or dispatch queues are defined as an object that manages the execution of tasks, serially or concurrently on your apps main thread or on background thread. Queues in GCD are just like real world queues. They use the first in, first out format. What this means is, the tasks submitted to the queues are worked on, based on the order they were put in. Some tasks are shorter than others and can be executed at the same time, therefore we can't guarantee they will finish in the same order they were submitted. Let's look at how we can create queues, specifically serial and concurrent queues. We're going to start with the serial queue. Serial queues execute tasks in the order they were added. Concurrent queues on the other hand, don't finish tasks in the order they were added. We will look at concurrency in detail in another module. We have learnt how to execute tasks one by one and also concurrently. Remember, the type of queue determines the execution policy. Sync waits for the block to complete, while Async does not. In your playground, let's create a serial queue. We are going to initialize the dispatch queue with just the label and name it serial. Let's now create a concurrent queue. You're going to use label and attribute as well. Let's confirm the type of queues we just created. As you can see, we have created both serial and concurrent queues. If you omit the attribute parameter for the concurrent queue, the dispatch queue will execute as a serial queue. We can now use the queues we just created to execute some tasks. For the serial queue, let's print one to four. And for the concurrent queue, let's print five to 10. Let's run the code. For the concurrent queue, it does not print out the numbers in the order we expect it to print out the orders, which is five, six, seven, eight, nine, 10. And this is because for concurrent queues, they don't finish tasks in the order that they were added.