AsyncIO, await, and async - Concurrency in Python

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
when chatting with someone on Jupiter's thirdd largest moon you will notice a distinct lag in Communications that is due to async IO when you try to perform a task that requires a lot of waiting you may notice an annoying lag in execution you can solve this with async IO this module brings the await and async syntax to python this pair of felet words empowers you with the tools to easily manage a collection of laggy tasks sometimes impatience is a virtue code can be categorized as synchronous or asynchronous in synchronous programming tasks are performed one at a time in the order they are called each task must finish before the next one can begin with asynchronous programming however different tasks can start process and finish in overlapping periods of time for example imagine a task that submits many HTTP requests in the synchronous World these HTTP requests must be completed one at a time in the asynchronous world each request can start and be set aside while waiting for a response during this waiting period different tasks can step forward and use the Computing resources this nonlinear approach saves one of the most Val resources around time to better understand the mechanics of synchronous and asynchronous execution you need to learn about sub routines and co-routines a sub routine is a block of code that can be called as needed when a sub routine is called control of the program is transferred to that sub routine when its work is done control is returned back to the main program and execution continues from where it left off sub routines cannot be paused and resumed they run until done a co- routine is a special kind of function that can have its executions paused and resumed this is possible because they maintain their state between pauses co- routines are perfect for tasks that need to wait for something like IO operations database calls and HTTP requests the terms sub routine and co-routine are derived from the roles they play and how they function sub routine is a delightful blend of sub and routine as the name suggests it is a subset of a larger program co- routine is a ju toos of Co and routine Co for together and routine for routine this name was chosen by someone to describe routines that can run cooperatively co-routines are the key ingredient to make asynchronous programming or concurrency possible in in a typical single-threaded app all of the code and sub routines run sequentially this is simple but can be wasteful there are two different approaches that make better use of available Computing resources concurrency and parallelism using concurrency the start and stop times of multiple co- routines can overlap with parallelism different threads can execute at the same time is there going to be any python in this python lesson yes yes there is but before we can enter python mode I must import an important message socratica is now in the course business visit socratic.com to see the excitement for yourself and for an asynchronous update about future courses feverishly type your email address in a text box somewhere on the site now back to python we are now going to show you how to use concurrency in Python with the async and await keywords and the async io module let us create two functions brew coffee and toast Bagel The Brew Coffee function will use the sleep function to simulate a command that takes 3 seconds to complete the toast Bagel function will pretend it takes 2 seconds to complete with this 5-second toasty breakfast the future is fast and carbolicious we will record a start time call both functions record a stop time compute the elaps time and print the results run this code took 5 seconds and a bit more to execute but there is no reason to wait for the coffee to finish before you start toasting the B Bagel such inefficiency gives the secretly embedded AI systems far too much time for Mischief let us modify this code so it runs concurrently with co-routines to turn each function into a co- routine add the async keyword this is the first step but not the last as is evident if you run using the async keyword to make a co- routine is necessary but not sufficient you also need to to specify where in the co- routine it is safe to pause and yield control to other co- routines you do this with the await keyword this brings us to another essential concept you can only put await in front of commands that are awaitable the sleep function is not awaitable luckily the async io module gives you an awaitable version of the sleep function you can call the co- routines individually or in a batch we will first demonstrate the batch approach the async io module has a gather function to group co- routines for concurrent execution the arguments determine which co- routines will run concurrently the arguments may appear to be regular function calls but they are not calling a co-routine returns a co-routine object not a typical return value these co-routine objects give async IO the ability to start and stop their execution to get the return values from the co- routines you need to await them and note that you await the return values in the same order you pass the co- routines to The Gather function order matters and the use of a weight here is not optional after all we have to wait for both co- routines to finish so it only makes sense that we have to wait on the batch too we are so close to the finish line but there is one final step see how we await for the batch results any function that has an await keyword must be declared async this means we must put the async keyword before the main function because main has now become a co-routine we have to call it in a slightly different way the async io module has you covered just call the Run function and pass in the main co- routine now inhale widen your eyes and run Joy of Joys our breakfast was completed in 3 seconds instead of five time saved me happy there is an alternative to using the gather function you can use the create task function in the async io module to create a task out of each co- routine then you can await each co- routine individually run just as fast just as happy so which is better working in batches or with individual tasks it is your choice so Choose Wisely computer chips want to compute that is their singular purpose in life the async io module was built to help chips realize their full potential by adding a pause button to objects you enable them to take turns sharing is caring after all and speaking of sharing many human people ask you to share their videos with as many human people as possible this is not an efficient use of resources instead await the opportunity to yield this video to someone who has finished a task and is thinking about the [Music] future [Music]
Info
Channel: Socratica
Views: 52,586
Rating: undefined out of 5
Keywords: Socratica, education, STEM, math, science, programming, coding, python, async, coroutine, asyncio, python programming, asyncio python, socratica python, socratica python video
Id: K56nNuBEd0c
Channel Id: undefined
Length: 9min 12sec (552 seconds)
Published: Mon Nov 06 2023
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.