 Welcome back everyone. This is Brian. We're talking about asynchronous code in this video. So what is a synchronous code? I'm sure you've heard this buzzword and everybody is throwing it around like it is just some magical thing Really ascent code runs in the same thread What yeah, that's right. It runs in the same thread It appears to be some voodoo magic where the code looks like it's running in a multi-threaded fashion But it's all on the same thread So what a sync does is it uses a co routine to run on the same thread. So in the background, it's really scheduling this stuff We're going to introduce some keywords, for example, async and a way to really describe this. But what we're talking about Let's say we had a few things like being one thing two and thing three And we wanted to run all of those At the same time well multi-threading comes to mind, but then when you have threads you have all this complexity like locking and crashes and joining and all this fun stuff that just really sucks. So What a sync does is it takes the same thread and it says you're not usually using the entire thread For example, something like this How much of that thread are we actually using here? Well, we're using the entire thread But how much work are we actually doing very little actually none because we're doing pass So what a synchronous will do is say, okay If there's any unused time because remember a thread is a slice of time on that cpu Go ahead and get that extra time and do something else so for example We could run this and this and this and this and we could just keep going And it would all appear to be running at the same time and really all it's doing is it's using the unused time on the same thread Let's dive in and take a look Okay, the first step in any application. You guessed it is the imports So i'm going to get a little copy and paste action off the side here We're going to use threading multi-processing. Now, wait a minute. We're talking about a sync Why are we using threading and multi-processing because I want to be able to display to you The thread and the process that we're running in and you're going to see that even though It appears like it's a multi-threaded application. It's all on the same thread in the same process And to display that we're going to use logging now from here We're going to add something new to our arsenal. I'm going to say import and we want async i o which stands for asynchronous input output async i o We're also going to use random our good old buddy the random generator And just for giggles because I know you love it. You just cannot get enough of it. We are going to Use logging so we're going to say logging basic config and we're going to configure this right here at the top So there's no mystery as to where it's getting configed I got some some really good user feedback where they said sir We don't understand how you're configuring logging. Can you explain it? So to overly simplify it's just right here at the very top Okay, let's go ahead and make our functions And this is going to be the bulk of the video. So I'm going to slow way down here I'm going to say def and let's make a display function and the whole point of this is to well display the log But I want to do this in a special manner What I want to do is say Thread name and you guess what we're about to do here and say threading dot current thread And we want to get the name And then we're going to get the process name And it's probably pretty obvious what I'm about to do here multiprocessing dot current process That name I just want to shove those in some variables. So we don't have some big long Line of code that we're looking at but you could very much condense that down into a one liner if you wanted to Then we're just going to say logging dot info We've covered logging to the point. It's almost ridiculous to even talk about it But basically at this point all we're going to do is shove this out into the log And we want to say the process name Slash We could put this really in any format we wanted Thread name and then whatever the actual message was Probably help if I put that correctly. There we go Very very simple display function Now from here, we're going to make an asynchronous function It's very complex. I want you to pay attention We're going to say async And then whatever our function is it's really that simple. I lied to you. It's not hard at all From here. It just looks like normal python But it's pretty important to note that this async keyword defines that we are going to have the ability to Run this function asynchronously doesn't mean we have to means we have the ability to we're telling python Modify this code when you do your magic under the hood so that we can run this asynchronously All right from here, we're going to say display And I want to go ahead and display the name plus Say starting I can actually spell the word There we go Keyboard has betrayed me and because we've started I want to know when we've finished And then we're going to well Do something and I don't really care what we do. We're in newbie land here. So we're just going to simulate some work Now we're going to introduce you another keyword When we're talking about asynchronous functions remember these will appear to run At the same time they're going to use that dead space in the thread timing on the cpu So anything that we're not currently chewing up on that cpu. It's going to shove that in there and try to run it We want to be able to synchronize Asynchronous code and to do that We're going to use the await keyword And this does very much what it looks like it will wait for a asynchronous function to complete for example We're going to say async i o That's sleep And that does exactly what you think it would it's a coroutine that completes after a given number of seconds Which basically means it's an asynchronous when you see coroutine. It's an asynchronous Sleep function that goes after a couple seconds So if you don't do the await you're either going to get an error Or it's just going to immediately jump to the next line because guess what this is now in a synchronous call All right, so let's go ahead and jump in here and i'm going to say random dot Let's do ran and i've been doing ran range, but i want to like mix it up a little bit here i'm going to do one to ten And really that's it. That's our worker function here. So this is an asynchronous function Now a little bit of Trickery here. It's an asynchronous function calling an asynchronous function You have to use the await keyword when you do this Otherwise you're going to have a bad time in async land because it's just going to plow forward and not even pay attention to you So let's go ahead and make another function here. I'm going to say async That's your big indicator that this is going to be asynchronous code We're going to define run async And I want a maximum that we can work with here Go and make a list of tasks and then for x in range To our max Let's say name equals And we want to just make some sort of string representation here so we can see what the heck is actually going on And then we're going to say task dot end So really we're just going to add to our list and we're going to create Some type of task And we're going to make an async i o dot Ensure future You want to make sure you have a future in life. So that's why you're learning programming But really what this thing does is it wraps a co routine or an asynchronous function Into an awaitable future. There's your keyword awaitable Meaning you can use the await keyword when calling this Really a lot of fancy jargon, but that's really what's going on there. So let's go ahead and make our co routine We're going to say work Name this is a little bit different than what we're used to we're actually giving it the function with the parameter Under the hood. What's happening here is python's going to wrap that whole co routine into a future and allow us to await for completion Seems pretty challenging, but it's super simple when you look at it Now we're going to go ahead and say Await because we want to await for all of them to get done async i o dot gather And what gather does is it, you know, just imagine asynchronous tasks are like a bag of marbles And you drop that bag of marbles on the floor and they go everywhere in all different directions So now you want to gather them all up And you're going to wait until you've got them gathered up. That's kind of the visual you'll get there But really what we're saying is wait on this asynchronous call Which is called gather, which is going to go through all of these tasks And make sure the future has finished Okay, no more screwing around. Let's do our main function here. Let's actually see this thing work here I'm gonna say main main Got a little main happy there And in here, we're going to go ahead and display That the main started Now because the main started I want to show the main finished that way we can see this thing in its life cycle Let's go ahead and run this real quick You can see main process main thread main started main finish So now we have the process the thread and then whatever we got there In here, this is where we're going to make this asynchronous magic really really happen The first thing we want to do is get an event loop So I'm going to say loop equals async i o dot it Event loop and if you don't know what an event loop is They're happening all the time As you're sitting there looking at the program on your computer, whether it's a desktop laptop mobile device doesn't matter There is a loop in the background, which very much looks like this while true And instead of pass it's got some special code that basically says let other things have the context of execution So we're going to get that special loop that's in the background And we're going to be able to manipulate that So now that we've got our loop It's actually very very simple We're going to run something until it's completed. So I'm going to say loop Dot run and you notice we got some options here run forever Run an executor and run until complete now I'm not going to really cover run an executor because it's a little bit more advanced Run forever though. This will make your application literally run forever. This will never stop And now it doesn't mean it's going to keep going if your computer's off It just means it's going to go until you forcibly stop the application So I'm just going to put a little note there will run forever But what is that really used for typically you'll see that In long running applications like tcp servers or things of that nature or database programs Or something that's going to wait and wait and wait and they call it the main event loop Where you're waiting on keyboard input or something like that We are going to do the opposite. We are going to loop only as long as we need to So we're going to go out here and we're going to say loop dot Run until complete Now you notice the first thing it wants Is some sort of future generator now future that sounds familiar. That's right We did that up here in this async gather So it's very simple at this point. We can just call our function run async 50 So what's going to happen when we run this? Well, it's going to go into our run async with a maximum 50 It's going to say 4x in range, which is 50 in this case And then it's going to just print that out and make sure that it runs This is really the tricky part right here. We're saying await async.io gather and gather is going to gather all of those tests We shoot out into the processor And collect them in a nice fashion for us to use Now before we really stop Talking and start running this thing. We want to do one more thing. We want to actually close the loop closing the loop will free up resources and it stops the loop from being able to run infinitely and things like that and it just says to Python and the computer that we are now done with that and we don't want to use it anymore. We're just going to close it out Think of it a lot like a file. We're now shutting that and we don't want to use it anymore All right, let's go ahead and clear this and let's see this thing in action. All right, so All right, so You see a bunch of gibberish here, but you should notice right before I even scroll up What's going on here main process main thread every single one of these main process main thread And i'm going to scroll up And the other major takeaway here is you see starting starts at zero and then they're sequential because we're starting these in a specific order But once we hit finish, you know, it goes from item one to item four This is where it really looks like it is multi-threaded. There's no guarantee in which order this is going to run The computer is going to decide which order to put it in This is extremely cool So let's go ahead and clear this and I want to run this again Just so you can see what's going on they all start and then the async io operations start finishing This is incredibly cool All right, major takeaway from this Asynchronous operations run in the same process same thread although it Takes out all the complexity of multi-threaded applications You do have to keep in mind a few different things. For example, you need the async keyword Which marks a function for asynchronous operations You need the await keyword, which will actually stop execution and say i'm going to await Or wait on the asynchronous function And we're talking about loops This is the application sitting there churning away in the background and waiting for something to complete when we're done with that loop we need to close it and Be very careful if you ever use run forever It will make your program look like it's locking up, but really it's just running an event loop in the background I hope you enjoyed this video You can find the source code out on github.com If you need additional help myself and thousands of other developers are hanging out in the void realm's facebook group This is a large group with lots of developers and we talk about everything technology related not just the technology that you just watched And if you want official training, I do develop courses out on udemy.com This is official classroom style training if you go out there and the course you're looking for is just simply not there Drop me a note. I'm either working on it or I will actually develop it I will put a link down below for all three of those and as always Help me help you smash that like and subscribe button The more popular these videos become the more I'll create and publish out on youtube. Thank you for watching