Main Thread, Sync vs Async and Deadlocks in Swift

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
hey guys welcome to my channel i code i am belov and today we are going to look at some of the favorite interview questions related to concurrency and more specifically main thread now these questions are asked in different ways like main dot sync versus vs main.async why is it necessary to update ui on main thread what will happen if we use sync on main thread etc i have been on both sides of interview table and i understand that these questions are really good ones and can be drilled to any depth so let's look at them in detail and because we are more comfortable in using dispatch.main.async or asynchronous blocks in general so let's explore the uncharted territory first let's dive into synchronous blocks to understand what is a synchronous block and what it can lead to let's write some synchronous code so for that i'm making a queue here just name it something else let's say my queue and dispatch queue i'll just label it my queue you're free to label it anything you want and let's write a synchronous block on it so i'll write myq dot and let's just put a print statement here saying hello well and let's give it a run okay so our log is there hello world is there and now let's take it a notch ahead and let's put another print statement in a synchronous block on the same queue so i'll just do my cue dot sing and another print statement saying hi there let's see what happens okay so we encountered a crash but why did it crash what went wrong so our first print statement it got executed hello world the log is there but on the very next line where we try to execute another synchronous block we encountered a crash you can pause the video for a while and give it a thought okay so the answer is deadlock now what is a deadlock so deadlock is a situation where two processes are waiting for a resource to free up but it's logically impossible for that resource to become available yes i understand that you have heard these words a million times so let's have a look at this video and then we'll write the code for it mr roy asks his office boy jon to bring movie tickets but forgets to mention the movie also he tells him to neither call him nor come empty-handed when jon reaches to counter the guy sitting there asks him the movie for which tickets are needed jon doesn't know the movie so he is asked to step aside but his boss asked him to not to come empty-handed he blocks the queue this results in a deadlock let's try and replicate the same scenario in our code so i'll just delete this code where we were having one queue and instead we will have 2q so we assume that driver and the booking counter both are working in a synchronous fashion so let's have two cues so one is let say booking counter booking counter q is equal to dispatch q say booking counter and other q say driver q is equal to dispatch q c driver now let's try to replicate the scenario so the first thing that driver does is it asks for the movie tickets so let's put a print statement for that give me give me tickets let's say until the time he won't get tickets he's not going to leave the queue as in the synchronous block will not finish and meanwhile the booking counter guy he asks for which movie so let's put a print statement for which movie so here driver cannot go back to his boss and ask for which movie because in our assumption driver is working synchronously so till that time this job is not completed he cannot take upon another job so this particular synchronous block till the time it is not finished driver is not going to leave the synchronous block so even if i go for writing say driver queue and sync print i'll ask the boss i'll ask the boss once you give me the tickets so till the time this job is not done this job will not get executed but let's try and see that what happens okay so the same exception we encountered again and the reason is deadlock now that we have an understanding of deadlock we can easily figure out this crash so the reason behind this crash is this block will not complete till the time this block is executed and this block cannot start its execution till the time this block is completed so both are dependent on each other and logically it's impossible to become available for any one of them so that's a deadlock now we have knowledge of how synchronous blocks work and what is a deadlock we can try understanding main.sync so when we write dispatch.main.sync we are blocking the only available thread keep it in mind that main queue is the serial cue and hence it has only one thread so if we write synchronous block on the main queue we are blocking the only available thread for the execution and hence it results in deadlock and eventually end up with crash i have heard many people saying that if we write synchronous block on the main queue it will freeze the ui no it will not just freeze the ui it will result in a crash now the last part of the video why ui should be updated on the main thread first ui kit is tied to main thread so any updation in the ui elements will be done through the run loop of the main thread or main run loop or we call it as viotron cycle we can even confirm this through a small piece of so here i am having a view some view i initialized it in a dispatch queue gave it a frame background color blue and added it as a sub view to the main view the main thread checker is giving us a warning but it's okay for us for now and also it is not the good practice to use self in the closures either it should have been like this we should have used capture list but just for the demo purpose i'm using self here it's not a good practice we should not do it like this but let's run it and i'm expecting that the view should be added okay the view is here now let's try changing its background color on a background thread so let's say if i go for creating another queue say q2 and on q2 if i try changing self dot some view dot background color is equal to dot green it works or not it did not so in nutshell we cannot update the ui on background thread let's try updating it on the main thread so instead of this q2 if i go for this patch queue dot main dot async and if i try here updating the background color let's see yes it does so the baseline is we cannot update the ui on the background thread and the reason is same that i mentioned earlier that the ui kit is tied up to the main thread the refreshing of the ui happens on the main run loop of the main thread what we call as view draw cycle and if you want to know more about this if you want to go crazy with the ideas that what if if i go for changing the ui kit if i go for making it thread safe can i update the ui in the background or how does the async displacement by facebook works i'll put some links in the description you can go through them they are really good articles and there's one more reason behind why we cannot update the ui on the background thread and that is graphics rendering so whenever we make some changes in a ui component it is re-rendered on the display for example say label its font will be rasterized the text will be converted into the pixels these pixels will be placed together on the display maybe 60 times a second lighting up of the pixels their placement all these should happen in one go so if we try making it asynchronous there are strong chances that we might end up having flickering because the part that is to be rendered might be in processing so it's a bad idea to update the ui on the background thread we must go for updating it on the main thread so that's pretty much for this video a new video comes every sunday so stay tuned let's write better code together happy coding
Info
Channel: iCode
Views: 2,730
Rating: undefined out of 5
Keywords: ios, Swift, Main Thread, Sync vs Asyc, DispathQueue.Main.Sync, DispatchQueue, UI update on main thread, concurrency, interview questions iOS, main queue, Run Loop, View Draw Cycle, Main Run Loop, iOS app development
Id: qv_1JC93NdE
Channel Id: undefined
Length: 9min 48sec (588 seconds)
Published: Sat Apr 03 2021
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.