Async Techniques and Examples in Python Transcripts
Chapter: Built on asyncio
Lecture: Demo: Cancellation with Trio

Login or purchase this course to watch this video and the rest of the course contents.
0:00 So we converted from asyncio to Trio and we saw things got simpler this async with block. The nursery concept is quite simple.
0:09 Let me show you how we can use that for even greater benefit. I talked about cancellation. Now watch this. Let's suppose we want this to run for either
0:18 five seconds and finish successfully or if it goes past five seconds we're going to cancel all the work. OK, even all the child tasks that maybe
0:25 those processes themselves kicked off. How'd we do that? It sounds complicated, right? Watch this. With trio.move_on_after, let's say 5.
0:37 How about that? Let's see what happens here. It should run for a little bit. Do some generating, do some producing, some consuming
0:44 and then it should cancel. So this line should print out in just about five seconds. Let's find out what happens, it's working, and it's working.
0:53 Five seconds are past, and boom. We ran out of time. We're done. We canceled them, straight away. How cool is that?
1:02 So if we make that less work, two, two, and four something like that, should be able to produce all the work and just finish early.
1:09 No cancellation, 2.42 seconds. But if it takes too long, this cancellation kicks in and off it goes. So these interesting coordination concepts
1:19 like to have this block only run for so long with some sort of time out, also if this thing kicks off
1:26 child tasks and then you decide to cancel it or time it out or something like that or this one has an error.
1:33 Even those get canceled if they're still running. There's really interesting stuff that happens around this behind the scenes that does happen
1:40 in normal asyncio, definitely doesn't happen in threading or multiprocessing that makes this a really nice coordination framework.
1:47 And that's Trio, like I said there's actually a lot more to it. You can build really interesting things from the ground up.
1:52 But I think this is enough to give you some inspiration and some ideas to go explore it if it's useful for you.

Talk Python's Mastodon Michael Kennedy's Mastodon