Grand Central Dispatch — concurrent and serial dispatch queues

Dispatch queues

Dispatch Queues are GCD structures used in order to execute and manage works. You can imagine work here as a task to be executed, as to get an image from the web, or to load a string and set it as the title of a view controller. Those works can be executed serially or concurrently in a queue. As the name ‘queue’ invoke, the works enqueued in these structures are executed in a FIFO order, which means, the first work enqueued will be the first executed. In this post we’re going to explain better what is a serial and concurrent queue.

Serial queues

The first type of concierge is the serial concierge. People will be in a queue in front of the restaurant’s door. They will tell him that they wanna eat. This concierge will open the door, but just one person will be able to get in the restaurant by time. He lets the first client get in. The client make it’s order, is served, eat, and then leave the restaurant. After the first client leaves the restaurant, the concierge will let the second get in. And the processed is repeated. Order, served, eat, leave, next one… The problem here is that it doesn’t matter how many tables this restaurant has. He will let just one client by time to get int. The good thing is that sometimes you can serve just one client by time.

Concurrent queues

In the other corner of the street is another restaurant. In this restaurant they have a concurrent concierge. The queue still the same. A lot of people willing to eat. But here the process is different, this concierge will let the first client get in, right after the second one, and the third one and so on. This is cool because a table will be empty only if they don’t have clients. The only problem is that sometimes it becomes a mess and the situation is out of control.

Which one is better?

Both types of queues are useful depending of the situation. For example, concurrent queues are super cool when you want to have independent work being executed at the same time. Serial queues are good for example to replace locks, since here you will have just one work being executed at time. So let’s say if you’re changing an array by more than one thread, and also reading it. If you wanna always get a consistent information, you should dispatch the work of write and read to a serial queue.

How to create a serial queue in Swift?

When you create a serial queue, it’s by default serial. So, the short way to create it is the one below:

How to create a concurrent queue in Swift?

The only different in between create a serial and a concurrent queue is that you have to say it’s concurrent in the attributes:

Computer Engineer + iOS Engineer. I am interested in Swift, Kotlin, Firebase, Data Structures, ASO & On Solving Real World Problems.

Computer Engineer + iOS Engineer. I am interested in Swift, Kotlin, Firebase, Data Structures, ASO & On Solving Real World Problems.