iOS Concurrency and Threading - iOS Interview Question - Swift
Вставка
- Опубліковано 10 жов 2024
- The next topic in my series on iOS Interview questions explains concurrency and threading in iOS and Swift. This iOS interview question was asked in quite a few interviews. In this concurrency and threading tutorial I explain what is going on at a high level to help you answer this interview question.
iOS Dev Courses - seanallen.teac...
This is part of a series of videos about iOS interview questions in Swift. Check out the overview where I list and briefly discuss all the topics that are in this series:
• iOS Interview Question...
Twitter:
Sean Allen - / seanallen_dev
Hired.com:
hired.com/x/1n01g
Book and learning recommendations that help out the channel if you decide to purchase (Affiliate Links):
Paul Hudson's Hacking With Swift:
gumroad.com/a/...
Donny Wals - Combine:
gumroad.com/a/...
Mark Moeyken’s SwiftUI Books:
www.bigmountainstudio.com/swiftui-views-book/fzc51
Objc.io Books (Thinking in SwiftUI & Advanced Swift):
gumroad.com/a/...
Ray Wenderlich Books:
store.raywende...
#swift #softwaredeveloper #iosdeveloper
Watch Next - iOS Take Home Project - Job Interview Practice - Free Preview - ua-cam.com/video/MSIe2y6Fee8/v-deo.html
Concurrency and Threading can be a tricky topic. Happy to help answer any questions in the comments!
Hi Sean, just to clarify, when we say DispatchQueue.main.async that async references the concurrent queue of the main thread, is that it? Does each thread has its own set of two queues (serial and concurrent)?
Excellent! Thanks for your video and work.
But i think we need part 2 with this title. It video skip more detail about multithreading. For example what is deadlock, more detail about flexibilities with Operation and OperationQueue. More detail about API GCD.
Maybe few word about api Thread and how depend Thread and DispatchQueue.
Dude you are an amazing teacher. I really enjoy your teach style, you bring real life examples into code and that really helps with bringing things into perspective. Thank you for taking your time out to teach us all of this. I have an interview tomorrow and I feel so much better now that i've seen your series and I know that i'm hitting on the right topics and that I actually understand them. Thank you bro
Happy to help. Glad you enjoyed the series!
Good luck! Hope it went well!
Hi Sean: Job well done. You obviously put quite a bit of time into this video. The explanation is very clear and understandable.
Thanks Richard, yeah... this was one tough to put together, but I think it turned out ok.
I am upset that 2 people have disliked this tutorial. I can not understand why. Anyway another great tutorial Sean. Keep it up
Haha, can't please them all, I guess... Thanks for the kind words, Ade!
It has something to do with the Star Wars I guess
Maybe they wanted an actual working sample code and not the same animations running 20 times and someone typing something and not just talking to the camera?
??? I don’t even know which video of mine this is referring to. The creator app doesn’t show me. I just know it’s an older video.
Thanks for the link. Julio misinterpreted the point of the video. This is part of my interview question playlist on how to answer questions you’ll be asked. When on phone screens for interviews they won’t ask you to code this kind of stuff. They’ll want you to explain concurrency and threading at a high level. This video isn’t meant to be a full-blown, in-depth coding tutorial. It’s meant to help newer developers understand the topic at a high level so they can explain it.
i have 8 years of experience in iOS and you videos are simple & great examples
I’m listening to this while I’m on my way to a technical interview after learning iOS Development for almost a year with zero coding background. Great stuff Sean!
Good luck on the interview!
@@seanallenThank you very much Sean. I got the job!!!
Looking forward to sharing my story on how I became an iOS dev within a year :D
That's awesome! Congrats!
@@wanted47 where is your story :D
He got busy developing stuff..#nostory
The car highway analogy is the best one I’ve heard so far. You are awesome! You always provide the best explanations
I've seen this video 3 years ago. Now again came here to recollect things. Thanks for making this video🙂
That was pretty solid explanation once again, I have been learning iOS Development for the past 6 months now and watched almost all of you videos, great work. Every time I learn at least a thing I did not know before. Thank you.
Glad you learned something, Alisher! Thanks for watching.
A lot of developers don't have a strong basic knowledge now days and this kind of videos really helps, appreciate it, like your videos, thanks man and keep going!
Thanks for the kind words, Tony!
Hey Sean, such an excellent explanation for me as a beginner developer. I wasn't expect that you use a lot of some kind of real-life example like the highway and the queue but you did, so that's nice and very much easy to understand compared to coding. Thank you very much and keep up the good works!
Thanks for the kind words. Happy hear you enjoyed the explanation 😀
you explained all this in a very simple manner...good job done
Thanks! Glad you liked it.
Wow this is awesome Sean. Nice use of animations and your explanation is very clear. Keep up the good work, Nice one here!!
Thanks Chilly! This was a tough one to put together.
I must say you will make a good bootcamp instructor or teacher too lol.
Thanks for video .
Its the best video about GCD I've ever seen.
The video is excellent , audio is great and you can show with animations and codes.
You're doing the fantastic work. Congratulations for your work
Thanks Marcos! This is one of my favorite videos that I've made. Glad you liked it!
DispatchQueue and OperationQueue are so important to learn and understand as an iOS / macOS dev!
Agreed!
Udacity and the big nerd ranch book on iOS programming have great lessons GCD and when to use operation queue vs. dispatch queue. FLOW is key.
Hi Michael, I have the book, but didn't find anything on GDC there at all. Can you reference the pages or section? There are a couple of pages about OperationQueue, but nothing on dispatch that I could find.
Such an intuitive approach to learn about concurrency and thread. Thank you Sean 🙌🏻
Great explanation, Sean. You are right that this is a tricky topic, but whatever you have mentioned in the video, it's more than enough for an iOS Developer to work on Apps.
Thanks for the kind words, Vandan. It was hard to figure out how to present this topic in the best way. Hope everyone likes it!
I just want to tell you that you are rock! I really love your courses, videos and contents. Keep going
In most cases you embed the switching to the main thread inside the background queue so you call and out layer asych and inside of it a switch to main queue asynch to update UI.
Sean, thank you for making these videos! Keep it up!
Glad you enjoyed it, Gene!
Great videos! I enjoy your paid courses as well! Very thorough and well executed Sean. Question: what are a list of tasks that happen on background threads vs a list of tasks that happen on main thread? My understanding is closures occur on a background thread and updating UI happen on main thread. Any other logic, tasks, methods etc that directly link to background thread or main thread? Basically, what are the dead giveaways in code that state,”This is background thread or main thread?”
Also, what allows you to see what thread something is occurring on? Is there code that will reveal that? Like code for checking type(of:) for data types tells the data type…is there something similar to understand which thread is used for code?
Great video Sean. I had a question: You mentioned that you don't manually put anything on the background queue as much...Why is that? I would say it is common practice to manually put API data fetching logic in the background queue. And the only reason one should have to call reloadData for the table view on the main queue is when something has already been put in the background queue (like a manual trigger to fetch data through some API)
Sean, your thoughts on this pease?
Excellent work! Animation and visual explanation helps a ton 😊
Thanks Filip! Glad you like it.
Hey Sean! Absolutely love your videos! Currently just went through a phone screen and 80% of the questions came from your videos so I'm really thankful! Just wondering, what you use to make your animations?
That's awesome to hear, Karo! Glad I could help in some way. Best of luck on the interview process! For the video animations I just used Key-Frame animations in Final Cut Pro.
This is a really good tutorial about concurrency. Thanks Sean.., great job.!!
Thanks Patrick!
wow Sean!! thanks so much for this video! it really cleared up my mind about this topic =) you've done an amazing job with this well didactic tutorial
finally i undestand the dispatch queue
two days ago, i trying to print the content size of tableview but idk it printed 0.0
and i think maybe the value is printed before the tableview load or get the total of content size.
and i got the solution in stackoverflow which is to use main dispatch queue and its worked perfectly.
so that the thread of print value has moved to main thread which is using the serial queue :)
That's a big concept to understand. Glad you got it!
What are a few examples of when you would use the serial queue? Would it be when you’re reloading a table view on the main thread? What are some other examples? Also what are a few examples of tasks to execute on a concurrent queue?
In the example you gave, you should add [weak self] in, because the user may chooser to go to a different page while your json data is being loaded. Once it's loaded, self is already removed from memory therefore will cause an error
This is correct
Thank you Sean, These videos are clear and so very helpful.
Happy to help, Charmi 😀
@@seanallen Omg, I was just watching your videos right now (almost since morning) and seeing your reply, I'm like 🤩
picture can tell thousands words. that picture of express lane(main thread) can have two cars (tasks) side by side. but main thread is an expressway with just one lane so no two cars (tasks) go side by side.
Hey Sean, great videos... very helpful.... Need a video of concurrency and multithreading with GCD and OperationQueues comparison, what n how more flexibilities we get with OperationQueues, etc.
Good suggestion. I'll add it to the list!
Great explain, especially the high way example, but what's the different between queues and thread? Seems they are doing the same purpose of concurrent queue and mutiple-thread...
Hi Sean. Keep up the good work!
Hey Eray... will do!
Hey Sean, great explanation and for so many of your videos, your analogies are what helps people like me understand these concepts so here, your traffic example or your other video explaining class vs struct with sharing google docs vs sending an email. My question is when do you use .async and .sync? Difference? I can google but your explanations are really helpful. Thanks in advance.
Synchronous and Asynchronous are basically the same as serial and concurrent, respectively in the video. Something done synchronously is like serial. One thing at a time, and the next task doesn't start until the one before it finishes. Whereas Asynchronously is like concurrent, multiple actions happening at the same time.
@@seanallen Hey! also does sync vs async refers to the task execution on a thread level compared to serial concurrent which is on dispatch queue level?
Like if we have a task/operation being submitted to a concurrent queue synchronously then does that mean that the task will be getting dispatched onto different threads, and those threads will get blocked until that task/operation has finished completely. That is, serial blocks queue from starting new tasks and sync blocks threads to include new tasks' execution in between by context switching?
Or does sync also blocks the dispatch queue only from starting new tasks? And, sync/async also operate on dispatch queue level only?
Love your videos! Thanks so much :D Do you have videos on MVC, MVVM, and other patterns? If not, can you please make a video on those topics?
Hi Sean, Thanks again for this tutorials, they are very helpful.
I will have an interview soon and I am concerned they may ask whats the difference between Dispatch Queue and NSOperations.
Can you share some light :D
Nice explanation. You convinced me that it was time to subscribe!
Man... that was a hard-earned subscriber, lol. Thanks Isaac! 😃
Lol! I am not much of a joiner. You gotta show me something!!
you put in a lot of effort, thanks man!!!
Glad you enjoyed it!
Imho, one thing hard to understand for beginners is calling Concurrent Queues “queue”. You can’t relate to it to a real life queue. So, it means I was not cutting in line in cafeteria, I was just in a concurrent queue.
Thank you for simplifying this.
thanks mate
Thanks! Glad you liked it!
wow impressive explanation Sean, good job!
Thanks Wilson... this one took some time to put together... Glad you enjoyed it!
just a small trick that i use (only for small projects, maybe using Firebase, etc. ) I load all the JSON data on the initial VC and make a global variable storing all the JSON values , so whenever you need the values you can simply call the global variable on the main thread. Tough this isn't a good programming technique , it works good enough
You are the Best iOS Developer i have ever seen
Hehe, I appreciate the kind words, but I still have a lot to learn myself. 😀
please do a video on GCD and Nsoperation queue.
Hi Sean! Which tasks get executed on the background thread and which tasks on the main thread? You mention UI related tasks should get executed on the main thread, but I am struggling to understand which tasks automatically are executed in the background.
Thanks for all of your help! I am huge fan on your videos.
Hey Lenny, the classic example of the background thread tasks are network calls. Because downloading data from a server takes time (who knows how good the internet connection is), that goes on the background thread as to not disrupt the app running on the main thread.
You didn't explain quite clearly, If we have 1 functions for sending tasks to main thread and 1 for background thread, then in which thread we are on?
You stated that you never manually sent tasks to the background, so I am assuming that there are conditions when tasks are automatically sent to a background. What are these conditions?
very simplified and clear thank you Sean
Glad it was helpful!
Sean, this video was 1000x times more powerful than the Stanford video out there in youtube for threads btw that video is more than an hour and it is not even 1%worth vs this. Again Thank you.
Now, how do I start debugging something that is stuck somewhere in the mainThread (serial) while just opening a vc that hangs just after viewWillAppear()? Thanks for giving me any clue!
Glad you liked this video! It's one of my favorites as well. I would need more specifics on your issue to be able to help. It's pretty hard trying to help debug via UA-cam comments 😀
Love your videos but please make this one with more code examples thank u
great explanation, now I know the differences between main and global (represent the threads on the device's processor), and concurrent and serial (represent the queue types in each thread ), hopefully I'm right
But what I'm confused about, is when I see serial.async, I know serial queue is meant to be one task at a time, how could it be asynchronized? the same for concurrent.sync, the main purpose of the concurrent is to execute multiple tasks at one time, then why would we make it synchronized?
Thank you Sean for your high-quality content
best,
You don't use the background thread when uploading or downloading data?
thank you. I learned a lot from this video
Thank you so much for this video!
Glad it was helpful!
Excellent post production skills
Thanks Misha!
Can we call APIs in Concurrent Queue? If yes, then will it help in case we have multiple APIs on same screen. Thanks!
Yes, you typically make network calls on a background thread (which is concurrent), then once you've received all your data from those network calls, you update your UI on the Main Thread.
I’m still confused because there’s a main thread and then there’s a main queue. And the there’s serial queues and concurrent queues. I don’t think you really tied everything together with dispatchqueue.main.async{}. Does the block of code have anything to do with the main thread or the main queue?
@Sean Allen
Hi Sean , I watched ur tutorial s , helps a lot, But have a doubt on one thing
# Dispatchqueue.main.async
"main" was mentioned it was serial queue ( order execution )
so, what the next .async ( it's unorder execution )
I was confusing ,pls clarify
You mixed up concurrency and parallism. And.... Without shared resource to protect, what is the CONDITION your thread race for to occupy it?
I don't understand code ); Is there anyway you can show me your path so I code just like you ?
Whats the difference between Operation and NSOperation?
What is the difference between gcd and queues??
In concurrency and asynchronous are the same? if not what is the difference?
If you have to send stuff to the main thread a lot, how is stuff sent to the background thread without sending it manually?
Great explanations.
Thank you
Happy to help.
Excellent job
you are an angel
Happy to help!
thanks for your time. i do have a question about uimapview, need it need to put to background thread ? if we put something on background thread, is there anything to do with weak reference ? so it may get dismissed and not occupy so many memory? sorry, i am a newbie, got all these silly question on my mind.
Hey Steven, this question is a little vague and hard to answer with out seeing your specific code. That being said, if you're handing your memory correctly and don't have retain cycles, what queue/thread it's on shouldn't make a difference.
How about semaphores and berries?
Awesome video Sean, thanks a ton.
Glad you liked it!
What would happen differently if the tableView was reloaded on the background thread?
It would take a lot longer to populate and would give your app the appearance of being really slow to load the images.
I experienced a bug recently which sort of made a concurrent queue to stop executing tasks altogether if the number of jobs submitted to it is >100ish. Can you throw some light on what might be causing this?
To be honest, Jatin, I'm not sure what could be causing that issue. Sorry I couldn't be of more help.
It's a great video! Do you have a video about lock & deadlock, race condition(with more details)?
Glad you liked it! I do not have a video on those topics.
Great expalanations
Shouldn't You use [weak self] in your self.tableView.reloadData() example?
how to work on a specific thread of the background thread ?
Great job Allen. .......
Excellent. Subscribed + Liked.
Thanks for the support, Roy 👍
Great job. well done and keep it up.
Thanks Saad!
Amazing video!!🍻
Thanks Rahul!
@Sean,
Thank you. Appreciate it a lot.
Glad you enjoyed it Joash!
excellent video, thank u so much
Happy to help, Andressa!
Great video Bro!
Thanks Eduardo!
I'm wondering why we use DispatchQueue.main.async() not DispatchQueue.main.sync()?
I was searching for an answer. but did not get promising answer. Hope you can help me out?
Even I do have confusion,
Anything know about this..?
Thank god..
What monitor are you using? Love your setup.
Hey Julio, it's an LG 34 inch curved ultra wide. Can see more about it in my Dev Setup video: ua-cam.com/video/ZiYx_4eeOms/v-deo.html
Sean Allen Sweet. Thanks!
Thanks man
Happy to help, Andre.
Nice video
Thanks 😀
If you say that you never use DispatchQueue.global.. but you do use DispathQueue.main, then how do you use it? I mean the whole point of dispatching to the main is switching from another queue but you say you don't use it..
When using NSURLSession for network calls the downloads automatically happen on a background thread. Which is why I rarely move stuff to a background thread manually (manually is the key word there). The very common flow is to download some data from the internet, and then update your UI on the main thread using DispatchQueue.main.async.
A follow up question, if you don't manually specify DispathQueue.main, will the UI continue being updated on the background thread?
It's not safe to update your UI in background thread, cause it is unpredictable when your UI gets loaded and it's not recommended, sometimes your app may crash for doing UI stuff in background thread.
Hello Sean, first of all thanks for great explanation. I've a question. I have whole bunch of data (around 300 images) to download and save to core data but when I save objects to core data on the main thread it takes so long and the UI gets frozen. Does that mean I can save core data inside "DispatchQueue.global(qos: .background).async" ?
I recommend split the process, for example download 10 object for time, and the others in a global queue
Hi Sean, what camera and microphone do you use for your videos?
I use a Canon EOS M3 and a simple RODE lapel mic.
Cool, it looks really nice! thank you!
very good 👍
thanks a lot :)
Can i check somehow on which queue my code is?
So just to confirm, any code executed on DispatchQueue.main.async {...} will be done in order?
You're making sure that code gets executed on the main thread. Yes, whatever code you have in that block will be executed in order.
But why is it .async if its eventually executed in order?
The async call will put some task in a dispatch queue and then return. Now the task will be executed asynchronously, in the order of the queue.
Is main thread free all the time and everthing else is happening on the background thread
UI stuff is happening on the main thread
@@seanallen Ok thanks sir for helping