Boudhayan Biswas
Jun 8 ยท 7 min read
Photo by Dan Gold on Unsplash

โ€œNow CPU can contain multiple cores and therefore we can run multiple threadsโ€ ๐Ÿ‘

Yes, It was one of the greatest improvements in technology. We use Dispatch Queue in Swift to create a new thread. Dispatch Queue, as the name suggests, it manages the execution of work items that are submitted to it.๐Ÿ‘

Stop here for a minute..๐Ÿšท๐Ÿšท๐Ÿšท

Before jumping into some serious kind of discussion and code, letโ€™s try to understand some concepts of threading in a funnier way, then it will be easier for us to digest. ๐Ÿ”๐ŸŸ๐Ÿณ๐Ÿ˜ฌ

We all know the terms Concurrency, Parallelism, Synchronous, Asynchronous in threading, but how are they different from each other?๐Ÿค”

Concurrency:

๐Ÿค˜Hurrah!!! Itโ€™s a nice weekend evening!! Itโ€™s raining outside also.๐ŸŒจโ›ˆ๐Ÿค˜

You are just enjoying the time and playing the guitar on your favourite song.๐ŸŽธ๐ŸŽง

A new notification in WhatsApp!! ๐Ÿ’Œ

OMG!! Itโ€™s a message from your girlfriend.๐Ÿ’žโค๏ธ๐Ÿ’“ Now, what would you do?๐Ÿƒโ€โ™‚๏ธ

You have to stop playing the guitar to reply to that message because you need to type by your hand only. You can not do the two things simultaneously.๐Ÿ˜ญ๐Ÿ˜ญ

You have replied to that message, now you started feeling more romantic!! ๐Ÿ’ž So you have started playing the guitar again. ๐ŸŽธ

You are playing the guitar while waiting for a new message, then you are replying to the messages for some time, and you are repeating the same thing over and over again until your romantic mode is gone.๐Ÿ™ˆ๐Ÿ™ˆ๐Ÿ™ˆ

In computer science, this is the same thing as concurrency where multiple tasks can be executed at the same time but not necessarily simultaneously.โœŒ๏ธ

Parallelism:

Another new message received!!๐Ÿ’Œ

Girlfriend: Enough messages!! Letโ€™s talk over the phone. I want to listen to what are you playing on guitar. Call me now.๐Ÿ“ฑโค๏ธ

Now you are on cloud nine ๐Ÿ˜œ๐ŸŒฅ

So you have dialled her number and started talking while you are playing the guitar on a beautiful romantic tune, just to make sure background music is enough to impress her.๐Ÿ˜‹๐ŸŽผ

You are talking over the phone as well as you are playing the guitar also. Now we can say you are doing two things in parallel.โ˜„๏ธ

In computer science parallelism means when the computer is doing two or more tasks simultaneously without any waiting.๐ŸŒž

Synchronous:

You have started enjoying the rainy evening more. ๐Ÿฅฐ๐Ÿฅฐ๐Ÿฅฐ Suddenly..๐Ÿคจ

Knock! Knock!๐Ÿง

It is your mom calling. Ohhh No!!!๐Ÿ˜ญ๐Ÿ˜ญ๐Ÿ˜ญ

She has asked you to go to the nearby supermarket to bring some vegetables for dinner.๐Ÿ˜ฌ๐Ÿ˜ฌ

Itโ€™s your momโ€™s order, how can you ignore?๐Ÿ˜ญ You must have to go otherwise you know what will happen to you.๐Ÿ˜ˆ

So you have to drop the call for some time because you have to go to the supermarket by bike and it is raining outside also.๐Ÿค•

So you drop the call saying that you will call again after one hour.๐Ÿ™‚

Here you can not do the two things at the same time. As you have to go to the market then after coming back only, you can call. So these tasks need to be executed in a proper order one by one.๐Ÿคจ

In synchronous programming, your program is executed line by line, one line at a time. Each time a function is called, a program execution waits until that function returns before continuing to the next line of code.โœŒ๏ธ

Asynchronous:

You have just come back from the market. ๐Ÿšถโ€โ™‚๏ธ

After entering the room, you have seen your mom has kept a pile of clothes on your bed.๐Ÿ’โ€โ™‚๏ธ๐Ÿ’โ€โ™‚๏ธ๐Ÿ’โ€โ™‚๏ธ

Ohh God! why??๐Ÿ˜ฉ๐Ÿ˜ฉ๐Ÿ˜ฉ

You have to wash those clothes now. So you put those clothes in the washing machine and have come back into the room without waiting there to complete.๐Ÿƒโ€โ™‚๏ธ

Checked the phone. 10 missed call from your girlfriend. ๐Ÿ˜ญ๐Ÿ˜ฌโ˜„๏ธ๐Ÿ”ฅ

You have told her that you would call after one hour.๐Ÿ”ฅ๐Ÿ”ฅ

So you dialled her number and started talking without waiting for the washing machine to complete.๐Ÿ˜‹

So here you are performing two tasks in an asynchronous way.

In asynchronous programming, you are essentially saying, โ€œI know this function call is going to take a great deal of time, but my program doesnโ€™t want to wait around while it executes.โ€. Asynchronous programming is a form of parallel programming that allows a unit of work to run separately from the primary application thread. When the work is complete, it notifies the main thread (as well as whether the work was completed or failed).๐Ÿค˜

I think the above examples helped you to understand the basic concepts. Now letโ€™s come back to the main topic and do some coding just to see how all of these concepts are working in a real programming environment.๐Ÿ˜Ž

DispatchQueue:

There are two types of DispatchQueue-

  1. Serial Queue (a work item starts to be executed once the previous one has finished execution)๐Ÿ‘
  2. Concurrent Queue (work items are executed concurrently)๐Ÿ’ช

It has also two dispatching technique, one is sync (it blocks the calling thread until execution doesnโ€™t finish)and another one is async (it doesnโ€™t block the calling thread). It takes a closure as an argument to execute. ๐Ÿ˜บ

Below is the example of a serial queue working asynchronously. Since it is a serial queue, all tasks are executed in the order they are originally added to the serial queue. Tasks executed serially are always executed one at a time by the single thread associated with the queue.๐Ÿšถโ€โ™€๏ธ๐Ÿƒโ€โ™€๏ธ๐Ÿƒโ€โ™‚๏ธ

Example of Serial Queue

Before starting the concurrent queue, we should know what is โ€œQOS (Quality of Services)โ€?๐Ÿ‘€

When we use a concurrent queue, that means multiple tasks are executed at the same time and sometimes itโ€™s necessary to prioritize a task because of its importance. Tasks in a queue are executed in decreasing order of priority. ๐Ÿ‘ฉโ€๐Ÿ‘ฉโ€๐Ÿ‘ง

So itโ€™s all about priority man!! ๐Ÿคจ๐Ÿคจ๐Ÿคจ

The importance and priority of a task represented by QoS.๐Ÿ˜Ž

To create a concurrent queue, we have to pass attributes as concurrent. As an additional feature, we can set the priority of the task by giving QoS. Remember in the concurrent queue, tasks are executed in the order they are added but with different threads attached to the queue. They are not supposed to finish the tasks as the order they are added. Order of task differs each time.๐Ÿง๐Ÿ˜ฏ

Letโ€™s take an example of a concurrent queue, if you look in the console, then you can see there that smile() and love() functions are executing in parallel.

Example of Concurrent Queue

These are the most basic things of Dispatch Queue. โœ…๐Ÿ’ฏ

Now letโ€™s discuss DispatchWorkItem, Semaphore, DispatchGroup and other advanced topics in DispatchQueue.๐Ÿ™

DispatchWorkItem:

DispatchWorkItem represents the work that is executed on a queue. We can submit the work item for execution to DispatchQueue or DispatchGroup, by doing this, it only specifies the executing queue or group. We can also call perform(), but it executes the work item on the calling thread only. The code snippet below is a basic example-

If you donโ€™t want instant execution of Work Item, not an issue, wait function is there to help you out. We can pass some time interval for the delay in execution.โ˜„๏ธ

OOPS, there are two types of wait function for DispatchWorkItem. Which one to use? Confused?๐Ÿ˜ฏ

func wait(timeout: DispatchTime) -> DispatchTimeoutResultfunc wait(wallTimeout: DispatchWallTime) -> DispatchTimeoutResult

DispatchTime:

DispatchTime is basically the time according to the device clock and if the device goes to sleep, the clock sleeps too. A perfect couple.๐Ÿ‘ญ

DispatchWallTime:

DispatchWallTime is the time according to the wall clock, who doesnโ€™t sleep at all. A Night Watch.โš”๏ธ

In the above extension, I have combined the functions in a single function to make it easier. You just need to pass the desired queue and time interval in the run function. If you donโ€™t pass the queue then it executes on the calling queue only.โœˆ๏ธ

After the execution, we can notify the same queue or another queue by calling

func notify(qos: DispatchQoS = default, flags: DispatchWorkItemFlags = default,queue: DispatchQueue, execute: @escaping () -> Void)

DispatchQoS class works with DispatchQueue, It helps in the categorization of the tasks according to their importance. The task with the highest priority executes first as the system assigns more resources for faster execution. But the task with lower priority executes later as it requires less number of resources and energy. It helps the application to become more responsive and energy efficient.๐Ÿ‘

DispatchWorkItemFlags:

DispatchWorkItemFlags is basically a set of unique options that can customize the behaviour of DispatchWorkItem. Depending on the flag value you provided, it decides whether to create a new thread or need to create a barrier.โœ…

At the end of this tutorial, I would say the concept multithreading is very daunting. So use the concept very carefully if you are working on a very large project.

I hope this tutorial helps you to understand the basics of DispatchWorkItem and the related functionalities to it. If you like this, donโ€™t forget to give a clap dude.

๐Ÿš€Good Night. Happy coding.๐Ÿš€

๐Ÿ™๐Ÿ™๐Ÿ™ Thank you for reading!! ๐Ÿ™๐Ÿ™๐Ÿ™

Swift India

Swift Developer Community in India ๐Ÿ‡ฎ๐Ÿ‡ณ

Boudhayan Biswas

Written by

Swift Developer. In love with Python & Machine Learning.

Swift India

Swift Developer Community in India ๐Ÿ‡ฎ๐Ÿ‡ณ

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and weโ€™ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium โ€” and support writers while youโ€™re at it. Just $5/month. Upgrade