Python 3, an Illustrated Tour Transcripts
Chapter: Asynchronous Programming
Lecture: asyncio When and Why
Login or
purchase this course
to watch this video and the rest of the course contents.
0:00
So Python provides in 3.6 these new keywords, async and await, and if you put async in front of a def that makes it a coroutine
0:11
that you can use in this asyncio framework, and when you want to hand off control of something else you call await.
0:18
So the benefit of this asyncio library is that it allows you to write asynchronous code in a sequential style. Remember I had that slide where I said
0:27
if you get rid of the async and the await, it looks sequential. There's other asynchronous libraries in Python
0:32
and many of them allow you to write asynchronous code but do so with callbacks and if you're familiar with callbacks that can get a little confusing,
0:40
and Guido van Rossum, the creator of Python who actually worked on asyncio for a long time, is not a big fan of callbacks,
0:47
and so he didn't really want to introduce callbacks into the standard library, but he wanted something that allowed us to take advantage
0:54
of asynchronous programming, but make it look as normal and someone who is used to Python programming can look at it and should be able
1:04
to wrap their head around what's going on there. Why or when would you want to take advantage of this? Again, if you have lots of io,
1:12
these asynchronous programs scale better than threads or processes. There is overhead to creating a thread in Python,
1:21
Python threads are native threads, they are operating system threads and there is overhead the order of megabytes per thread.
1:28
And so if you've got thousands of requests coming in to a web server or whatnot, you've got each of those as a thread,
1:36
each of those is going to have some overhead to it and a process has even more overhead than a thread does.
1:43
But if you have stuff that has a lot of io latency such as a server or whatnot,
1:48
then you can use these native threads or this asynchronous style programming to scale better, but one thing to be aware of is that your whole stack
1:57
basically needs to be asyncio aware. Once you put code in there that blocks or just takes up the CPU and doesn't allow anything else to run
2:06
you're going to have throughput that's going to suffer because it's not going to allow other code to run.
2:11
So you really need to have code that has awaits in it and allows other code to run. So some of the components that you all need,
2:20
we need a function that will suspend and resume these co-routines. We need an event loop that keeps track of the functions and their states
2:25
and we'll run them and manage them. If we have long-running CPU tasks, these need to call await. So the other code can run or else we need to use
2:35
what's called an executor to run those in their own thread so that they don't interrupt or basically block the asynchronous code from running.