Python 3, an Illustrated Tour Transcripts
Chapter: Asynchronous Programming
Lecture: Cooperative Multitasking, Async Version
0:00 So again, if you're using asyncio, all your code needs to be infected or whatnot, everything a coroutine calls should be async if you're awaiting it,
0:10 it can call other functions if it's just calling them directly and getting the results.
0:13 But if you're calling another coroutine, then you need to await that or you need to iterate over the results of those.
0:18 So if I want to convert this prior code that I have, to use asyncio rather than the little framework I had,
0:24 what I need to do is I'm going to replace def async_ and I'm just going to put async def and I'm going to create a coroutine
0:31 and then instead of yield, I had yield in there, if you have yield or yield from I'm going to replace that with await
0:38 and then I'm going to pass in a future to get back the results. So the code will change slightly but it should be very similar.
0:44 So we'll see here that I have now acync amap and I'm passing in a future here, but I still have a function and the sequence
0:51 and then I'm looping over my sequence and I'm appending the result of my function and then at this point, I'm calling await and I'm sleeping for 0
1:00 what sleeping for 0 on asyncio effectively does is it says you know what, give someone else a chance to run.
1:07 And so this is the point where someone else can run their code, and then at the end when I'm done,
1:13 I'm just going to stick onto my future the results that I got. So I'm going to create an event loop,
1:17 I'm going to create a future to hold the result of my first guy, I am going to create another future to hold my result of my second guy
1:24 and I'll pass those in and I'll have to coroutines, one called t1 and one called t2. And then I'm going to call an asyncio function called gather
1:33 that takes multiple co-routines and gives me a future and then I'm just going to on my loop here say
1:39 run until complete this coroutine that has both of them in there, and then at that point, when that's done, it will return
1:45 and I can say f1 give me the result, here's the result from f1 and here's the result from f 2 and I can close my loop if I want to at the end there.
1:53 So again, there's a few things that you need for your asyncio code. You need to have an event loop, so you create a loop,
1:59 you call run until complete and then when you're done, you close it. Pretty straightforward, but again, you need to have co-routines
2:07 and you need to have an event loop that can manage and run those for you. So that's the basic steps that we do for using our event loop.