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,
0:04 everything a coroutine calls should be async if you're awaiting it,
0:09 it can call other functions if it's just calling them directly and getting the results.
0:12 But if you're calling another coroutine, then you need to await that
0:15 or you need to iterate over the results of those.
0:17 So if I want to convert this prior code that I have,
0:20 to use asyncio rather than the little framework I had,
0:23 what I need to do is I'm going to replace def async_
0:26 and I'm just going to put async def and I'm going to create a coroutine
0:30 and then instead of yield, I had yield in there,
0:33 if you have yield or yield from I'm going to replace that with await
0:37 and then I'm going to pass in a future to get back the results.
0:40 So the code will change slightly but it should be very similar.
0:43 So we'll see here that I have now acync amap
0:47 and I'm passing in a future here, but I still have a function and the sequence
0:50 and then I'm looping over my sequence
0:53 and I'm appending the result of my function
0:55 and then at this point, I'm calling await and I'm sleeping for 0
0:59 what sleeping for 0 on asyncio effectively does
1:03 is it says you know what, give someone else a chance to run.
1:06 And so this is the point where someone else can run their code,
1:09 and then at the end when I'm done,
1:12 I'm just going to stick onto my future the results that I got.
1:14 So I'm going to create an event loop,
1:16 I'm going to create a future to hold the result of my first guy,
1:20 I am going to create another future to hold my result of my second guy
1:23 and I'll pass those in and I'll have to coroutines,
1:26 one called t1 and one called t2.
1:28 And then I'm going to call an asyncio function called gather
1:32 that takes multiple co-routines and gives me a future
1:35 and then I'm just going to on my loop here say
1:38 run until complete this coroutine that has both of them in there,
1:41 and then at that point, when that's done, it will return
1:44 and I can say f1 give me the result, here's the result from f1
1:48 and here's the result from f 2 and I can close my loop if I want to at the end there.
1:52 So again, there's a few things that you need for your asyncio code.
1:56 You need to have an event loop, so you create a loop,
1:58 you call run until complete and then when you're done, you close it.
2:03 Pretty straightforward, but again, you need to have co-routines
2:06 and you need to have an event loop that can manage and run those for you.
2:09 So that's the basic steps that we do for using our event loop.